Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

angularjs - How to use $http promise response outside success handler

$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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

pic

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*");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...