angularjs – 在加载资源之前等待承诺解析

前端之家收集整理的这篇文章主要介绍了angularjs – 在加载资源之前等待承诺解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的一个AngularJS控制器包含以下行:
api.tickets.query()

api模块包含:

angular.module('myapp.api',[
  'ngResource'
])

.factory('api',function($resource,applicationsService) {

  function fetchAppId() {
    return applicationsService.getCurrentApp();
  }

  return {
    tickets: $resource('tickets',{
      applicationId: fetchAppId
    }),...
  }

applicationsService.getCurrentApp()自己进行$http调用.所以你也许可以看到问题 – 这个调用可能在fetchAppId()返回时没有得到解决.

我怎么能绕过这个?

让我们说通过异步方式从applicationsService返回的数据是:
var data = [
    {
        "PreAlertInventory": "5.000000","SharesInInventory": "3.000000","TotalSharesSold": "2.000000"
    }

和applicationsService工厂返回承诺:

.factory('applicationsService',['$resource','$q',$q) {
    var data = [
    {
        "PreAlertInventory": "5.000000","TotalSharesSold": "2.000000"
    }
    ];   

       var factory = {
            getCurrentApp: function () {
                var deferred = $q.defer();   

              deferred.resolve(data);

                return deferred.promise;
            }
        }
        return factory;
}]);

我会打电话给api.tickets()

$scope.data = api.tickets();

但是我们的api服务看起来像:

.factory('api',applicationsService,$q,$timeout) {

  function fetchAppId() {      
      return applicationsService.getCurrentApp();
  }

  return {
 tickets: function() {
         var deferred=$q.defer();
        fetchAppId().then(function(data) { // promise callback
            $timeout(function(){         // added dummy timeout to simulate delay
                    deferred.resolve(data);    
                },3000);                    
        });
        return deferred.promise;
     }
   }
});

演示Fiddle

原文链接:https://www.f2er.com/angularjs/141326.html

猜你在找的Angularjs相关文章