I've tried searching through StackOverflow regarding this issue but could not find a solution that worked for me. I'm using AngularJS. I have simple controller that calls a http service and reads the response data. In this specific case, I have a JSON output with an objects array I am unable to read.
Here's the JSON output:
{
"results": [{
"id": "1",
"download_url": "",
"uploader": {
"id": "114899"
},
"uploaded": "1442599380",
"streaming_url_timeout": 1446092554
}, {
"id": "2",
"download_url": "",
"uploader": {
"id": "114899"
},
"uploaded": "1442599380",
"streaming_url_timeout": 1446092554
}]
}
I'm trying to get access to items in 'results'. This is my Service that retrieves the JSON data:
this.getUData = function() {
var deferred = $q.defer();
$http.jsonp(API_URL + 'udata')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
And then this is how i call this service from my controller:
myservices.getUData().then(function(data) {
$scope.uitems = data.results;
});
Template:
<div class="item" href="#" ng-repeat="item in uitems">
<h2>{{item.id}}</h2>
</div>
But when I try to access the items in 'results', I get the following error:
Uncaught SyntaxError: Unexpected token :
The line in question for this error is "results":[
Looks like in this case the callback function was not working correctly on the PHP server so I managed to get away by using the 'GET' method in the $http service like so:
this.getUData = function() {
var deferred = $q.defer();
$http({method: 'GET', url: API_URL + 'udata'})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
Related
Would like to get the return object from an HTTP request into another scope object so I can use it in HTML with ng-repeat directive. How can I get the returned object into a variable?
Call HTTP Function
Get Data
Store response
Make scope variable the value of the HTTP response
JS:
angular.module('myApp').controller('ItemController',[
'$scope', '$http', '$location',
function($scope, $http, $location){
var currentLocation = $location.path();
$scope.getItem = function(){
$http.get('path/to/json/file.json').then(
function(response){
$scope.results = response.data;
console.log('item controller, item:', $scope.results);
});
};
$scope.item = //MAKE THIS VALUE OF THE RETURN OBJECT FROM getItem
console.log('scope.item', $scope.item);
}
]);
JSON
[
{
"first_name": "Mega",
"last_name": "Man",
"image": "http://placehold.it/75x75"
}
]
HTML
Would like to be able to just have
<p>{{item.first_name}}</p>
<p>{{item.last_name}}</p>
<img ng-src="{{item.image}}"/>
Updated JS Call
$scope.getItem = function(){
$http.get('path/to/json/file.json')
.success(function(data){
$scope.results=data;
console.log('$scope.results: ',$scope.results);
}).error(function(data){
console.log(data);
}).then(
function(){
$scope.item = $scope.results;
console.log('$scope.item: ', $scope.results);
});
};
You can do it in different ways one way is to use success and error callback functions like:
$http.get('path/to/json/file.json')
.success(function (data, status, header, config) {
$scope.results =data;
console.log('item controller, item:', $scope.results);
})
.error(function (data, status, header, config) {
console.log(data);
});
Another option is using then promise function like:
$http({method: 'GET', url: 'path/to/json/file.json').
then(function(response) {
$scope.results = response.data;
console.log('item controller, item:', $scope.results);
}, function(response) {
console.log(response);
});
The issue that was happening what getting callbacks to work correctly. Replaced the .then() method with .success() and .error(). Since the object that was getting called was an array it could not be parsed out in the HTML to get object properties. The other part that was needed was in the success callback to get the first object of the array with $scope.results=data[0]
$scope.getItem = function(){
$http.get('path/to/json/file.json')
.success(function(data){
$scope.results=data[0];
console.log('$scope.results: ',$scope.results);
}).error(function(data){
console.log(data);
});
};
I've create a function in angular. And it is working fine and can get correct result but my problem is i want particular node from result. i have worked with JSON and Jquery, but i am new in angular.
This is my code.
$scope.booking= function(docid,addid){
//console.log(addid);
var a = $http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
//$scope.count= response.data;
/*$scope.appo=[];
$scope.appo= i;
i++;*/
//
//console.clear();
return response.data;
});
console.log(a);
return a;
};
http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php
return following json.
{
"status":"success",
"message":"",
"booking":{
"booking_detail":[{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
This how i can see in firebug
Expanded view
so i want to get value(which I've highlighted in image) from response(which is under $$state), what should i do?
in short how can i get bottom result?
{
"status":"success",
"message":"",
"booking":{
"booking_detail": [{
"session":null,
"slot":null,
"day":"Friday"
}]
}
}
$http service returns a promise(this is printed in your console logs), which will be resolved after that http call is complete.
Please go through this $q documentation on how deferred data works.
https://docs.angularjs.org/api/ng/service/$q
This should work,
$scope.booking= function(docid,addid){
$http({
method: 'POST',
url: "http://localhost:81/DoctorStayServiceAngular/model/getDoctorBookingDetail.php",
params:{"doctorid":docid,"addressid":addid,"day":weekday[d.getDay()]}
//params:{"doctorid":docid}
}).then(function mySucces(response) {
$scope.responseData = response.data;
});
};
After this you can bind the data in responseData to your view.
I have tried to pass the customer class object to Asp.net MVC controller using angularJS $http service.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{
$scope.getRecord = function () {
$scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };
$http({ url: "Home/GetCustbyID",
method: "GET",
params: {objCustomer: $scope.objCustomer} })
.then(function (response)
{
//success code
};});
}});
Controller Action is defined like:
public JsonResult GetCustbyID(Customer objCustomer)
{
return Json(objCustomer, JsonRequestBehavior.AllowGet);
}
However in the above controller action customer object is always passed as null. Did i miss anything?
Please help me guys to resolve this.
You should use a POST request if you wish to send multiple parameters at once in a JSON object in your AJAX request and capture that as an Object on your server side.
$http.post(url, $scope.objCustomer)
.then(successCallback, errorCallback);
As you are actually sending data to server you are posting in $http.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{
$scope.getRecord = function () {
$scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };
$http({
url: "Home/GetCustbyID",
method: "POST",
data: $.param({ objCustomer : $scope.objCustomer })
})
.then(function(response) {
//success code
};});
}});
in other case if you like to send/pass data as json string you will have to use stringify like this
var data = $.param({
json: JSON.stringify({
name: $scope.name
})
});
$http.post("/path_of_controller", data).success(function(data, status) {
//do whatever you like
})
I am dealing with a little issue, and need some help.
I have an API setup, works just fine.
Now I want to get a single object using its ID. I have tried using $http, but could't get it to work. So I switched back to $resource. Here is what I have in my service file.
getPlatesInSelectedContainer: function() {
return $resource('/api/v1/platesincontainer/:id', {id: "#id" },{
get: { cache: true, method: 'GET' }
});
},
And in controller I am reaching to function doing so.
CleaningPlatesFactory.getPlatesInSelectedContainer({id : 1}, function(data){
$scope.plates = data;
console.log(data);
})
But this is not returning any results. What I am doing wrong?
UPDATE
Earlier I have tried $http but getting this.
I would still get $http to work. It's as simple as this:
getPlatesInSelectedContainer: function(data) {
return $http.get('/api/v1/platesincontainer/' + data.id);
}
You need to accept the data object in your service function.
Inside the service:
getPlatesInSelectedContainer: function(data) {
return $resource('/api/v1/platesincontainer/:id', {id: data.id },{
get: { cache: true, method: 'GET' }
});
}
Then call it like this:
getPlatesInSelectedContainer({ id: 123 })
I am using a angular $resource like the one below.
angular.module('app')
.factory('data', function ($resource) {
var Con = $resource('/api/data', {}, {
update : {method : 'PUT'}
});
return {
getData : function (user_id, callback) {
return Con.query({user_id : user_id}, function (data) {
cb(data); // (breakpoint) HERE data is not good
}, function (err) {
cb(err);
}).$promise;
}
};
});
This is what I get when a put a breakpoint on data :
[
['w','e','l','c','o','m','e'],
['h','e','l','l','o']
]
howerver, the server sends :
['welcome','hello']
anyone know why the strings get split?
Thank you
You've run into a fun bug with angular's $resource where it cannot handle a raw array of strings; as a workaround, you can do one of three things:
use the $http service instead
send an object-wrapped response via the server eg: { "stuff" : [ "your", "strings" ] }
force the response data into the above format client-side; $resource eg: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }} and then access it as data.list
See my answer at https://stackoverflow.com/a/22491240/626810
This works for RAW response. This is a slightly different version from the answer above but this is generic and is not only dependent on JSON response. This will basically mutate RAW response to String format. You will need to access $resource promise result as result.responseData
getAPIService() {
return this.$resource(this.apiUrl, {}, {
save: {
method: 'POST',
headers: {
'Accept': 'text/plain, text/xml',
'Content-Type': 'text/xml'
},
transformResponse: function (data) { return { responseData: data.toString() } }
}
});
}
Use $http instead of $resource
getRiskCount: function (Id,Type) {
var deferred = $q.defer();
var resource = $resource(urlResolverFactory.hostUrl() + '/api/getstudentriskcount',
{}, { query: { method: 'GET', isArray: false } }
);
resource.query({ userId: Id,userType: Type }, function (data) {
deferred.resolve(data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
Result - ['4','5','6','7']
getRiskCount: function (Id,Type) {
var apiUrl = urlResolverFactory.hostUrl() + '/api/getstudentriskcount';
apiUrl += '?userId=' + Id,
apiUrl += '&userType=' + Type;
var deferred = $q.defer();
var promise = $http({
method: 'GET',
url: apiUrl,
}).success(function (data) {
deferred.resolve(data);
}).error(function (data, status) {
deferred.reject(data);
});
return promise;
}
Result - [4567]