Angularjs的异步API请求

Asynchronous API Request by Angularjs

本文关键字:请求 API 异步 Angularjs      更新时间:2023-09-26

我有两个文件foo.js和foo.html。

在foo.js中,我从API获取信息(我假设它是异步的),foo.html可以访问该对象。

  <tr data-ng-repeat="y in vm.apidata">
                                    <td>{{y.name}}</td>
                                    <td>{{y.is_closed}}</td>
                                </tr>

但在这里我什么也看不见<代码显示这一点没有错,我将信息作为对象数组>

我正确地从API获取信息,但vm.apidata没有初始化,因此我可以在foo.html.中显示它

我如何确保它已显示?

@Aqsan,我会把它写在一个答案中,因为它对注释来说太冗长了。

我的假设是,你必须调用$scope$在外部代码完成任务时,或者在感兴趣的scope对象vm.apidata发生突变时,执行digest/$apply()。

重要提示:Angular希望vm.apidata是一个作用域对象。简单地放入全局窗口/自作用域并不是您的标记所引用的内容。

window.vm.apidata!=scope.vm.apidata

如果确实正确地更新了作用域节点,那么可以使用相同的作用域引用来调用作用域$apply()。

然而,如果你不在下面是一些信息。阅读有关Scopes的更多信息。

您可以注入对$rootScope的引用,这是服务(提供程序、工厂)、控制器指令中的顶级根作用域。类似地,层次感兴趣的$scope控制器指令相关,并且可以在那里注入,因此scope对象在父子层次结构中继承(级联),但可以在自定义指令或ng重复指令中实现的隔离作用域除外。为了简单起见,我将为您提供一个Controller实现的框架,您可以在其中实现连接:

var myModule = angular.module('myModule', []);
// This is a Service
// observe how you inject the root scope
// the array wrapper around the factory is for JS code minification protection which might name your parameter to something shorter and make it invalid (AngularJS-wise)
myModule.factory('retrieveService', ['$rootScope', '$q', function($rootScope, $q) {
  function retrieve(){
    // perhaps return a promise using the injected (light-weight) angular $q service
    var deferred = $q.defer();
    // Your external code can go in here for retrieval
    // When your async code complete call for success
    deferred.resolve(<yourapidata>);
    // alternatively for error
    deferred.reject(<yourerror>);
    // of course you could also just set the value to the $rootScope.vm.apidata here and call $apply
    $rootScope.vm.apidata = <yourapidata>;
    $rootScope.$apply();

    return deferred.promise;
  }
  return retrieve;
  }]);
// This is a Controller
myModule.controller('MyCtrl', ['$rootScope', '$scope', 'retrieveService', '$q', function(rootScope, $scope, retrieveSvc, $q) {
  function retrieve(){
    // Your external code could go in here inside the controller too
    // upon async retrieval perhaps...
    $scope.vm.apidata = <yourvalue>
  }
  // given you take care of your async call using promises and/or callbacks
  retrieveService().then(function(apidata) {
    $scope.vm.apidata = apidata;
    // though $scope is recommended imho, alternatively
    // you could bind the vm.apidata to $rootScope (here or in your service) as well which $scope will inherit
    $rootScope.vm.apidata = apidata;
  });
}])

有很多东西需要学习/扩展,排列也很广泛,但希望这能给你一个好的总体方向$http angular服务可能是一个不错的选择,这取决于您的后端api。

这听起来像是$apply()和/或$watch的作业——一个示例线程可能是AngularJS$location.path(path)在第一次时没有更新