I use the the simplest $http.get().then construction, but errorCallback is never called (checked with 500 and 404 error code)
$http.get(url,{cache: pageCache}).then(
function(data){
console.log('getPage.SUCCESS');
console.log(data);
console.log(data.data);
},
function(data){
console.log("ERROR");
console.log(data);
}
);
HTTP HEADERS
I also tried success/error - but the same issue is arrised
As described here, interceptor's responseError function have to be ended with return $q.reject(rejection);
One of my interceptors didn't follow this rule and cause all this mess
It may be that you are using the .then function which returns an object called response that contains several objects one of which is data.
The following is an example from https://docs.angularjs.org/api/ng/service/$http
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object contains a status object, angular uses this to run either the success callback or the error callback.
Then to access your data object use response.data, or what I like to do is have a service that returns only what I need to avoid confusion in the controller.
Related
In my controller i want send a request using get method if $http, in that get method i want to send the sessionID in headers. Below am giving the code snippet please check.
this.surveyList = function () {
//return session;
return $http.get('http://op.1pt.mobi/V3.0/api/Survey/Surveys', {headers: { 'sessionID': $scope.sessionid}})
.then(function(response){
return response.data;
}, function(error){
return error;
});
}
but this is not working when i send this vale in backend they getting null.
So how to resolve this.
we have a issue where the api is getting called twice from angular , however it works only once when called with the POSTMAN. And here with the custom header passed to the api, the action is called twice. What could be the reason for it?
Try in this way,
$http({
method: 'GET',
url: 'http://op.1pt.mobi/V3.0/api/Survey/Surveys',
headers: {
'sessionId': $scope.sessionid
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs,
// or server returns response with an error status.
});
I have read a lot of posts on promises,resolving promises, and accessing the data however I cannot seem to. Following some posts on Stack Overflow has just caused errors, so I am not sure what exactly I am doing wrong.
I have a function like so:
function getJsonl() {
var deferred = $q.defer();
$http({
url: 'urlNotShownForSecurity',
dataType:"json",
method: 'GET',
data:{"requestId":"123"},
headers:{"Content-Type":"application/json","requestId":"123"},
}).success(function(data) {
deferred.resolve(data);
console.log(data)
}).error(function(error,status,headers,config) {
deferred.reject(error);
});
return Promise.resolve(deferred.promise);
}
Here I return a json promise that has been resolved resulting in a json object I believe.
Printing to console I get the following:
Inside data is the information I need, it looks like this:
data:Array[8]
0:Object
description:"My description paragraph"
I have tried things with the returned object in my controller like:
vm.result = data.data[0].description;
vm.result = data[0].description
I have tried many different approaches in the view as well to access but I get 2 blank li tags and that is it.
I would like to be able to access the data so I populate a table. So if I can use it with ng repeat that would be great, as well as being able to access without because some data is used in more than just the table.
Update
#DanKing, following your implementation I get the following output in console:
Now I am back with a promise object.
It looks to me as though you're fundamentally misunderstanding the nature of promises.
$http() is an asynchronous function - that means it doesn't complete straight away, which is why it returns a promise.
It looks to me as though you're trying to call $http() and then get the result back and return it from your getJson1() method, before $http() has finished executing.
You can't do that. Your getJson1() method should just return the promise, so your calling method can chain onto it - like this:
getJson1().then(function(data) {
// do some other stuff with the data
});
The whole point of promise chains is that they don't execute straightaway - instead you provide callback functions that will be executed at some indeterminate point in the future, when the previous operation completes.
Your getJson1() function just needs to do this:
return $http({
url: 'urlNotShownForSecurity',
dataType:"json",
method: 'GET',
data:{"requestId":"123"},
headers:{"Content-Type":"application/json","requestId":"123"},
});
getJsonl().then(function(data){
console.log(data);
},function(err){
console.log(err);
})
should work. Where is your $http request and where is your call to getJsonl() will also make a difference. So choose that carefully when implementation. If you are using this in a service then you will have to return the function result say
this.somefunction = function (){
return getJonl();
}
and in your controller inject the service and do the following
service.somefunction().then(function(data){
console.log(data);
},function(err){
console.log(err);
})
Ok, rewrote the answer as a complete component to show the moving parts.
$http returns a promise so your original getJsonl call can be simplified. Using your original $http parameters this should dump your API response to the screen if you use the <json-thing> tag:
angular.module('yourModuleName')
.component('jsonThing', {
template: '<pre>{{$ctrl.thing|json}}</pre>',
controller: function ($http) {
var $ctrl = this;
getJsonl()
.then(function (response) {
console.log(response); // we have the $http result here
$ctrl.thing = response.data; // allow the template access
}, function (error) {
console.log(error); // api call failed
});
// call backend server and return a promise of incoming data
function getJsonl() {
return $http({
url: 'urlNotShownForSecurity',
dataType: 'json',
method: 'GET',
data: { requestId: '123'},
headers: { 'Content-Type': 'application/json', requestId: '123'}
});
}
}
});
$scope.tempObject = {};
$http({
method: 'GET',
url: '/myRestUrl'
}).then(function successCallback(response) {
$scope.tempObject = response
console.log("Temp Object in successCallback ", $scope.tempObject);
}, function errorCallback(response) {
});
console.log("Temp Object outside $http ", $scope.tempObject);
I am getting response in successCallback but
not getting $scope.tempObject outside $http. its showing undefined.
How to access response or $scope.tempObject after $http
But if I want to use $scope.tempObject after callback so how can I use it. ?
You need to chain from the httpPromise. Save the httpPromise and return the value to the onFullfilled handler function.
//save httpPromise for chaining
var httpPromise = $http({
method: 'GET',
url: '/myRestUrl'
}).then(function onFulfilledHandler(response) {
$scope.tempObject = response
console.log("Temp Object in successCallback ", $scope.tempObject);
//return object for chaining
return $scope.tempObject;
});
Then outside you chain from the httpPromise.
httpPromise.then (function (tempObject) {
console.log("Temp Object outside $http ", tempObject);
});
For more information, see AngularJS $q Service API Reference -- chaining promises.
It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.1
Explaination of Promise-Based Asynchronous Operations
console.log("Part1");
console.log("Part2");
var promise = $http.get(url);
promise.then(function successHandler(response){
console.log("Part3");
});
console.log("Part4");
The console log for "Part4" doesn't have to wait for the data to come back from the server. It executes immediately after the XHR starts. The console log for "Part3" is inside a success handler function that is held by the $q service and invoked after data has arrived from the server and the XHR completes.
Demo
console.log("Part 1");
console.log("Part 2");
var promise = new Promise(r=>r());
promise.then(function() {
console.log("Part 3");
});
console.log("Part *4*");
Additional Resources
Angular execution order with $q
What is the explicit promise construction antipattern and how do I avoid it?
Why are angular $http success/error methods deprecated? Removed from v1.6?
How is javascript asynchronous AND single threaded?
Ninja Squad -- Traps, anti-patterns and tips about AngularJS promisesGood theory but needs to be updated to use .then and .catch methods.
You're Missing the Point of Promises
$http call is async call. The callback function executes when it has returned a response. Meanwhile the rest of the function keeps executing and logs $scope.tempObject as {}.
When the $http is resolved then only $scope.tempObject is set.
Angular will bind the changed value automatically using two way binding.
{{tempObject}} in the view will update itself.
if you want to use tempObject after callback then do this
then(function(data){
onSuccess(data);
},function(){
});
function onSuccess(data){
// do something
}
Try to use a $scope.$apply before to finish the successCallback function. An other solution is to change successCallback -> function so:
$http({ method: 'GET', url: '/myRestUrl' }).then(function(success) { $scope.tempObject = success; console.log("Temp Object in successCallback ", $scope.tempObject); }, function(error) { });
Currently I've got this:
$http({
method: 'POST',
url: 'http://api-endpoint/somescript/',
data: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
});
If the script on the other end works out ok, then gets called. However, let's say the script on the server end has some sort of error that's not properly caught. If I make up an error by tossing in some garbage call like asdfasdf(), the then function isn't called, and instead I get this in the browser console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).
How do I catch this in the Angular code so I can handle it in a user-friendly manner?
EDIT: This is not a duplicate, as it is specific to Angular.
The $q.then() method accepts three function parameters, the first being the handler for a successful callbacks, the second being for errors, and the third being for notify. $http leverages $q behind the scenes so this thenable should behave like the documentation suggests.
To handle errors in the above code, just toss in an additional function for error handling as such:
.then(function (response) {
console.log(response);
}, function(response) {
console.log(response);
});
Feel free to browse the $q documentation, specifically The Promise API, for additional details.
To handle this, we will have to add a service/factory to intercept http calls. You can do it like this in your config
$httpProvider.interceptors.push('httpRequestInterceptor');
Now, the above service will be something like this
angular.module("app").factory('httpRequestInterceptor', function ($q) {
return {
'request': function (config) {
// Extract request information
return config || $q.when(config);
},
'responseError': function(rejection) {
// Extract response error information and handle errors
return $q.reject(rejection);
}
}
});
i am trying to post my form data via service but if i am trying to get the response in console i am finding undefined can you suggest me what mistake i am committing,
i am new to angular so finding difficult to catch the issue.Here is my code
commonApp.service('CommonServices',function($http){
this.saveData=function(DataToInsert){
$http({
method :"POST",
data :DataToInsert,
url : 'myurl',
//headers :{'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(programApiResponse){
console.log(programApiResponse);
return programApiResponse;
}).error(function(programApiResponse){
return programApiResponse;
});
};
});
and my controller
$scope.makeprogram=function(){
//console.log($scope.programdata);
$scope.ProgInsResponse=CommonServices.saveData($scope.programdata);
console.log('1'+$scope.ProgInsResponse);
}
You aren't returning the promise at
this.saveData = function(DataToInsert){
$http({
...
This should probably be
this.saveData=function(DataToInsert){
return $http({
...
Then if you can add your own handlers
CommonServices.saveData($scope.programdata)
.then(...)
Last but not least if you have a half decent browser you can just log objects, don't log strings.
CommonServices.saveData($scope.programdata)
.then(function(){
console.log(arguments);
});
This is async nature issue. Try this
$scope.makeprogram=function(){
CommonServices.saveData($scope.programdata).then(function() {
console.log('1'+$scope.ProgInsResponse);
});
}
Since you are returning promise you need to wait before response comes.