Home Ask Login Register

Developers Planet

Your answer is one click away!

ojus kulkarni February 2016

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

$scope.tempObject = {};

   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


Amit Dhaka February 2016

$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



function onSuccess(data){
// do something

Compa88 February 2016

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) { }); 

georgeawg February 2016

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

Post Status

Asked in February 2016
Viewed 2,141 times
Voted 7
Answered 3 times


Leave an answer

Quote of the day: live life