小编典典

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

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

我得到了回应,successCallback但没有得到$scope.tempObject外界$http。其显示undefined

如何访问response$scope.tempObject之后$http


阅读 247

收藏
2020-07-04

共1个答案

小编典典

但是,如果我想在回调后使用$ scope.tempObject,那么该如何使用它。?

您需要 从httpPromise。保存httpPromise并将该值 返回 到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服务API参考-
链接promises》

可以创建任何长度的链,并且由于一个承诺可以用另一个承诺解决(这将进一步推迟其解决方案),因此可以在链中的任何点暂停/推迟对承诺的解决。这样就可以实现功能强大的API。1个


基于承诺的异步操作的解释

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

图片

“ Part4”的控制台日志不必等待数据从服务器返回。XHR 启动 后立即执行。“ Part3”的控制台日志位于成功处理程序函数内部,该函数由$
q服务
保留,并
从服务器到达数据并且XHR 完成 调用。

演示版

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