$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。
successCallback
$scope.tempObject
$http
undefined
如何访问response或$scope.tempObject之后$http
response
但是,如果我想在回调后使用$ 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*");