如何在成功处理程序之外使用 $http promise 响应

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

我在 successCallback 收到回复,但是 $scope.tempObject 不在 $http 之外。它显示 undefined.

如何在 $http

之后访问 response$scope.tempObject

$http调用是异步调用。回调函数在返回响应时执行。同时,该函数的其余部分继续执行并将 $scope.tempObject 记录为 {}。 当 $http 被解析时,只有 $scope.tempObject 被设置。 Angular 将使用双向绑定自动绑定更改的值。

视图中的{{tempObject}} 将自行更新。

如果你想在回调后使用 tempObject 那么这样做

then(function(data){
   onSuccess(data);
},function(){

});

function onSuccess(data){
// do something
}

尝试在完成successCallback函数之前使用$scope.$apply。另一种解决方案是更改 successCallback -> function so:

$http({ method: 'GET', url: '/myRestUrl' }).then(function(success) { $scope.tempObject = success; console.log("Temp Object in successCallback ", $scope.tempObject); }, function(error) { }); 

But if I want to use $scope.tempObject after callback so how can I use it. ?

您需要从 httpPromise 链接。将 httpPromise 和 return 值保存到 onFullfilled 处理函数。

//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;

});

然后在你之外 从 httpPromise 链

httpPromise.then (function (tempObject) {
    console.log("Temp Object outside $http ", tempObject);
});

有关详细信息,请参阅 AngularJS $q Service API Reference -- chaining promises

可以创建任意长度的链,并且由于一个 promise 可以用另一个 promise 解决(这将进一步推迟其解决方案),因此可以 pause/defer 在任何时候解决 promise连锁,链条。这使得实现强大的 API 成为可能。1


基于 Promise 的异步操作的解释

console.log("Part1");
console.log("Part2");
var promise = $http.get(url);
promise.then(function successHandler(response){
    console.log("Part3");
});
console.log("Part4");

"Part4" 的控制台日志不必等待数据从服务器返回。它在 XHR starts 后立即执行。 "Part3" 的控制台日志位于 $q service 持有的成功处理程序函数中,并在 数据从服务器和 XHR [=64] 到达后调用 =]完成

演示

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


其他资源