Unable to resolve $$state in angularjs http call - angularjs

I have been trying to make an http call for a while but I am stuck here as I am not able to resolve the actual data value from the returned $$state variable. This is my code:
function (action, req){
var myData = $http.post('../rest/'+action, req)
.then(function(response) {
var data= response.data;
console.log("data: "+data); //1st console
return data;
},
function(response) {
alert(JSON.stringify(response));
});
console.log(myData); //2nd console
}
In the first console the values comes out to be fine as:
data: This is my data.
However when I return the same value and print it in the second console it is wrapped up in a $$state object. This is my second console:
d { $$state={...}, then=function(), catch=function(), more...}
When i expand it i get this value(in window>d):
Please help. What i need to do next to get $$state.value or d.$$state.value?

Related

AngularJS Http get empty first time

I have this code
PedidosService.getProductbyID($scope.listProductos.ProductID).then(function (d) {
$scope.oneProduct = d.data.producto;
});
PedidosService is the name of my factory, getProductbyId is my http get request and $scope.oneProduct is the variable where i want store the result of this request.
factory.getProductbyID = function (id) {
return $http.get('/Pedidos/GetProduct/' + id);
}
factory is my Factory and getProductbyID is my function to call http request
I call this code in a button. The first time that I click in the button, it returns a empty response '[]' but the next times that I click the button, it works fine!!!.
Thanks for you help
As far as I know the $http.get returns a promise because that call is asynchronous. With that in mind a typical call to $http.get should be something like this:
$http.get('/someUrl', config).then(successCallback, errorCallback);
In your context I would have done it this way, so the factory returns a promise and in your controllers you will handle the success and error callback appropriately:
factory.getProductbyID = function (id) {
var deffered = $q.defer();
$http.get('/Pedidos/GetProduct/'+ id)
.then(function (result) {
deffered.resolve(result);
}, function (data) {
deffered.reject(data);
});
return deffered.promise;
}

not able to push the data in to the list

I have one list which contains list of objects so, now i want to add one more object to the each list in the main list
I am using AngularJS
here is the code which i tried
$scope.mediaList = [];
$scope.getTheProfile = function(data){
for(var i in data)
{
ProfileService.getByHandle(data[i].handle,function(profiledata)
{
$scope.mediaList[i].displayName = profiledata.name.displayName
},
function(data , status){
console.log("In Error");
if(status == '400'){
$scope.errors.push(data["ERROR"])
}
},
function(data , status){
console.log("In forbidden")
})
}
alert($scope.mediaList[0].displayName)
}
so i am trying to add displayName to that list
now the problem is i am not able to get the value in that alert
if that alert is inside ProfileService.getByHandle function then i am getting the value
this is the function getByHandle
this.getByHandle = function(handle, successCB, errorCB, forbiddenCB) {
console.log("In Profile Service for fetching the profile by handle: "+handle);
HttpCommunicationUtil.doGet(apiConstants["profile"]["getByHandle"]+"/"+handle, successCB, errorCB, forbiddenCB);
};
Looking at getByHandle, it seems you are making asynchronous HTTP request using HttpCommunicationUtil.doGet.
What happens is this: for loop will make the HTTP calls and trigger this alert alert($scope.mediaList[0].displayName) without waiting for the response of getByHandle, as it's an asynchronous request.
Therefore, when you try to alert there will be an empty array [] value for $scope.mediaList due to line#1. So $scope.mediaList[0].displayName will produce error saying unable to get displayName of undefined.
You can return promises in ProfileService.getByHandleand when it's resolved use .then to update your variable.
If you can post code for HttpCommunicationUtil.doGet it'll be more useful.
EDIT:
Without HttpCommunicationUtil.doGet, I'll give you an idea of how to do it in a generic way.
Service:
this.getByHandle : function(params) {
return $http.get('/api/endpoint');
}
Controller:
ProfileService.getByHandle(params).then(function(data){
//use data to push response in $scope.mediaList[i]
});

unable to display the http get response from the factory in controller in Angularjs application

In my service I making http get request as shown below:
.factory('InvoicesGeneralService', function ($http) {
return {
getAgreementsByCourierId: function (courierId) {
console.log("Courier in Services" + courierId);
return $http.get('/api/agreements/byCourierId', {params: {courierId: courierId}}).then(function (response) {
return response;
});
}
};
});
And in browser console I am seeing the following response :
[
{
"id":3,
"number":"AGR53786",
"ediNumber":"EDI7365",
"startDate":"2012-09-02",
"endDate":"2018-07-01",
"courier":{
"id":2,
"name":"FedEx",
"url":"www.fedex.com",
"isActive":true,
"isParcel":true
},
"client":{
"id":4,
"code":"KJGTR",
"name":"Hearty",
"isActive":true,
"engageDate":"2011-07-07",
"isSendRemittance":true,
"upsUserName":"Tkd",
"upsPassword":"kuu",
"isEligibleForTracking":true,
"isEligibleForAuditing":true,
"status":5
}
}
]
And in my controller I am assigning it to result List :
$scope.resultList = InvoicesGeneralService.getAgreementsByCourierId(selCourierId);
But my resultList is always appearing as Empty. Can any one help me, why it is happening?
When I am trying to display resultList as shown below, it always shows empty object, {}. It supposed to display the response json array from the service but it is showing empty object.
<pre class="code"> {{resultList | json}}</pre>
$http returns a promise. Anything consuming that data needs to handle it like a promise too.
InvoicesGeneralService.getAgreementsByCourierId(selCourierId).then(function(data) {
$scope.resultList = data;
});
Also, your factory's then function is not doing anything at the moment. You should return the response's data from it.
return $http.get('/api/agreements/byCourierId', {params: {courierId: courierId}}).then(function (response) {
return response.data;
});

catch errors/read status code from rest call - angular

How do you catch errors/read http status code when making a rest call in one of these formats, both work to return a successful response, just no idea how to grab the info i need. I can get the object with values returned as I need, I just cant get the http status code.
methods provided by #Claies in a response to this question (Get data from $resource response in angular factory)
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query().$promise.then(function(response){
});
};
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query({}, function() {
})
};
I have tried to use the first method here and grab something from the function(response) such as response.status, but it returns undefined.
For reference, using this factory:
.factory("Item", function($resource) {
var endpoint = "http://some valid url";
function makeRestCallWithHeaders(id1, id2) {
return $resource(endpoint, null, {
query: {
method: 'GET',
headers: {
'id1': id1,
'id2': id2
}
}
})
}
var item = {
makeRestCallWithHeaders: makeRestCallWithHeaders
}
return item ;
})
Item returns something like this:
{firstName:Joe, lastName:smith}
I am really just trying to figure out how I can access the status code returned by the REST call. Absolute end goal is to read any error response and return error to UI written in angular as well. If there is a way to just read this in the UI, that could work too.
To read the error status you need to pass in the errorCallback to the $promise:
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query().$promise.then(
function(response){
//this is the successCallback
//response.status & response.statusText do not exist here by default
//because you don't really need them - the call succeeded
//see rest of answer below if you really need to do this
// but be sure you really do...
},
function(repsonse) {
//this is the errorCallback
//response.status === code
//response.statusText === status text!
//so to get the status code you could do this:
var statusCode = response.status;
}
);
};
You shouldn't need the status in the successCallback, because it is a success and you know the success code implicitly.
Therefore the status is not available in the successCallback by default.
If, for some reason, you do need the status in your successCallback, you could write an interceptor to put this information somewhere, but be aware that the angular framework deals with the data differently in different success scenarios so you will need to write code for different cases.

$http.jsonp not wrapping angular.callbacks

My function
$scope.doCall = function(){
console.log('test');
$http.jsonp('http://api.v2.quran.com/info/surah?callback=JSON_CALLBACK').
success(function(data) {
// this callback will be called asynchronously
// when the response is available
console.log(data[0]);
})
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data);
});
}
When I look at my network, the second call wraps angular.callbacks._1(OBJECT) while the first just returns [...ARRAY OF OBJECTS...]
The second will output in my console, the first is not doing anything! How can i make it work!
Thats API problem, http://api.v2.quran.com didn't wrap JSON to JSON_CALLBACK, in second case JSON starts with JSON_CALLBACK({... but in first case you get pure JSON, not JSONP. Try to fix it on server.

Resources