I'm at a loss on this. I have checked the forums and can't seem to find a solution.
I'm working on creating an ionic app to pull json feeds into the app and have them process. I have one feed setup, in one angular module, that is pulling some data perfectly fine. But when I try to create this second module, the feed var it errors, but if I hard code the URL in the $http.get it works fine.
This code errors with TypeError: Cannot read property 'protocol' of undefined:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get(listings[section])
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
However, making the following change to the $http.get works:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get("http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2")
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
I can't seem to figure out what I've got wrong in my code.
Here is the controller that is running that feed. It works perfectly fine when the URL is hardcoded.
angular.module('mwre.controllers', [])
.controller('PropertiesCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.items = [];
$scope.successGetPropertiesContent = function(data) {
$scope.maxIntro = 100;
$scope.items = data.properties;
for (var i = 0; i < $scope.items.length; i++) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.replace(/<[^>]+>/gm, '');
if ($scope.items[i].smalldesc.length > $scope.maxIntro) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.substr(0, $scope.maxIntro) + '...';
}
}
};
$scope.errorGetPropertiesContent = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property category content',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property category content');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertiesContent($stateParams.propertiesId, $scope.successGetPropertiesContent, $scope.errorGetPropertiesContent);
$scope.goToContent = function(id) {
$state.go('app.properties', { propertiesId: id });
};
})
.controller('PropertyCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.item = null;
$scope.successGetPropertyItem = function(data) {
$scope.item = data;
};
$scope.errorGetPropertyItem = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property listing',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property listing');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertyItem($stateParams.propertyId, $scope.successGetPropertyItem, $scope.errorGetPropertyItem);
});
Related
This is my factory service and it is fetching data from a web service
var customersFactory = function ($http) {
var customer = [];
var getCustomersURL = "http://localhost:50340/Services/CustomerService.asmx/GetCustomers";
customer.XMLtoJSON = function (data) {
data = data.replace('<?xml version="1.0" encoding="utf-8"?>', ''); ;
data = data.replace('<string xmlns="http://tempuri.org/">', '').replace('</string>', '');
return $.parseJSON(data);
};
customer.GetCustomers = function () {
$http.post(getCustomersURL).success(function (data, status, headers, config) {
return customer.XMLtoJSON(data);
}).error(function (ata, status, headers, config) { });
};
return customer;
};
app.factory('customersFactory', customersFactory);
Now, this is being used in my controller
app.controller("CustomersController", function ($scope, customersFactory) {
var service = [];
service = customersFactory.GetCustomers();
$scope.Customers = service;
if ((typeof (service) != 'undefined') && service.length > 0) {
service.then(function (result) {
$scope.Customers = result;
});
}
});
The value of service is always undefined or empty. Data is not being passed from factory to controller. Im calling a simple web service, no fancy APIs or WCF.
It there was some static/dummy data, its working fine. The controller is fetching the data and is being displayed.
Where am I doing wrong?
Any help is greatly appreciated.
Thank you
change this line var customer = []; to this var customer = {};
Or better yet make it a class...
change this to return the promise:
customer.GetCustomers = function () {
return $http.post(getCustomersURL).error(function (data, status, headers, config) { });
};
and usage in the controller:
app.controller("CustomersController", function($scope, customersFactory) {
$scope.Customers = [];
customersFactory.getCustomers().success(function(data, status, headers, config) {
$scope.Customers = customersFactory.XMLtoJSON(data);
});
});
I'm new to JavaScript and AngularJS. I'm tryin' to build up a very simple CRUD application. Here is the code of my controller:
(function() {
var app = angular.module('form.user', []);
app.directive('formusergui', [function(){
return {
restrict: 'E',
templateUrl: './js/views/user.form.html',
controller: function($scope, $http) {
this.formToBean = function() {
var ent = {};
ent.id = null;
ent.name = $scope.name;
ent.desc = $scope.desc;
ent.reg = Date.now;
ent.linkImgProfile = null;
ent.type = null;
return ent;
};
this.create = function() {
$http.post('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
this.delete = function() {
$http.delete('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
...
},
controllerAs: 'userForm'
};
}]);
})();
formToBean function collects data by the form. As the create function works well (REST service is called), the delete function broke with this error:
TypeError: Cannot assign to read only property 'method' of {"id":null,"name":"john","desc":"doe","linkImgProfile":null,"type":null}
I found similar questions about this kind of error but still I can't get what's going wrong.
for the delete method in the $http, the second parameter is a configuration, in your request instead of configuration related data, simple the json object is passed, refer the api for the $http.delete
https://docs.angularjs.org/api/ng/service/$http#delete
$http.delete('./services/users/:idtodelete')
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
});
So i'm busy with a webapplication and i'm stuck now with parsing an object. What I just tried to do is getting the ID of all results but it gives me undefined back in my console.
What did i try:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
$scope.id = data.results.id;
//Do i need a foreach here because it doesn't loop through all records and it gives me undefined.
$http.get('http:/api/id/' + $scope.id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
console.log(data);
//this returns the complete JSON
});
}).
error(function(data, status, headers, config) {
//handle errors
});
});
the first http.get loops through a JSON like:
"results": [
{
"easy": false,
"id": 1,
"title": "title",
},
{
"easy": false,
"id": 2,
"title": "title",
},
{
"easy": true,
"id": 2,
"title": "title",
}
]
and what the second on needs to do is get all of the ID's from the JSON and start a new GET:
$http.get('http:/api/id/' + $scope.id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
console.log(data.data);
});
})
the problem is that is, is that $scope.id = data.results.id; is returing nothing, do i need a foreach or something to loop through it all?
And displaying it i did try:
<div ng-repeat="detail in details">
{{ detail }}
{{ detail.adult }}
</div>
but is does not display anything (fyi i changed $scope.id = data.results.id; to $scope.id = data.results[0].id; to test it)
the JSON for the second GET looks like:
{
"adult": false,
"collection": {
"id": 131295,
"name": "Collection",
},
"levels": [{
"id": 28
}, {
"id": 12
}, {
"id": 878
}],
"homepage": "google",
"id": 100402,
"overview": "lorem ipsum"
}
i can't access the object with {{ detail.adult }} for example.
The reason why data.results.id is returning nothing is because data.results is an Array of objects. If what you want is an Array with the IDs of the objects of data.results you could do it like this:
var resultIDs = data.results.map(function(result){return result.id;});
I'm not sure, but I think that this is what you want:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [];
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
for(var i =0;i<$scope.games.lenght;i++){
$http.get('http:/api/id/' + $scope.games[i].id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details.push(data);
});
}
}).
error(function(data, status, headers, config) {
//handle errors
});
});
However I would check if the API that you are using has a method that accepts an array of IDs instead of a single ID, so that you don't have to iterate like that.
If this API is a RESTful service you could do it without iterating, like this:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [];
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
var resultIDs = data.results.map(function(result){return result.id;});
$http.get('http:/api?id=' + resultIDs.join(',') + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
});
}).
error(function(data, status, headers, config) {
//handle errors
});
});
I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});
Im trying to receive data posted by Angular:
$scope.add = function() {
$http.post($rootScope.appUrl + '/nao/test', {"data": "fiskapa"})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status) {
//Göra något
});
};
The problem is that fiskapa is not returned:
public function create($data)
{
return new JsonModel(array("data" => $data));
}
Data that is returned: Object { data=[0]}
You can get directly the json post:
$data = json_decode(file_get_contents('php://input'),TRUE);
Please, try this.