我一直在从事 Angular JS 项目。
在此,我需要调用 get 方法来获取一些记录,然后我需要将响应分配给作用域变量并将其显示给用户。
但我的问题是 HTTP get 请求延迟完成。所以我的作用域的值是未定义的。
下面是我的代码 Controller 代码:
var app = angular.module('falconeApp',[]);
app.controller("logicCtrl",['$scope','getDestinationService', function($scope, getDestinationService){
$scope.destinations = getDestinationService.getDestinations();
}]);
app.factory("getDestinationService",function($http, $q){
var getDestinationApi = "https://findfalcone.herokuapp.com/planets";
return {
getDestinations: function(){
$http.get(getDestinationApi)
.then(function(response) {
return response.data;
});
}
}
});
因此,正如您在上面的情况中所看到的,$scope.destinations 未定义,因为 HTTP 请求的完成时间晚于为其分配值。
有人可以帮我解决这个问题吗?
最佳答案
您还需要在 Controller 端添加 promise 回调。
The then() method returns a Promise.The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
app.controller("logicCtrl", ['$scope', 'getDestinationService', function($scope, getDestinationService) {
$scope.getDestinations = function() {
getDestinationService.getDestinations().then(function(res) {
$scope.destinations = res;
});
};
$scope.getDestinations();
}]);
关于javascript - Http get 请求的完成时间晚于范围在 Angular JS 中获取值的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48089489/