ojus kulkarni ojus kulkarni - 3 months ago 26
AngularJS Question

How to use $http.successCallback response outside callback in angularJs

$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

Answer

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;


}, function errorCallback(response) {

});

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


Additional Resources