javascript - Http get 请求的完成时间晚于范围在 Angular JS 中获取值的时间

标签 javascript angularjs

我一直在从事 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/

相关文章:

javascript - Bootstrap 开关 setState 给出 js 错误

javascript - 针对原生 js 的 angular json 相关函数

javascript - AngularJS 从指令更新作用域变量

javascript - 如何使用 angular-ui-bootstrap 根据屏幕分辨率在垂直药丸和选项卡之间正确交换?

javascript - 使用 google-code-prettify 美化代码的滚动条

javascript - 来自 table<tr> 循环的 HTML/Javascript/jQuery 数据

javascript - 查看 GWT 应用程序的所有 javascript 变量

javascript - 使用正则表达式将单引号更改为双引号

javascript - AngularJS 重定向闪烁以前的模板