1

我需要使用 $resource 提供程序对我的网络服务执行 http 调用。我想先解析来自 http 调用的数据,然后将此结果注入控制器。考虑到 OcLazyLoad 我刚刚写了这段代码。在我看来,它应该:

  • 首次加载服务;
  • 进行http调用;
  • 当 promise 解决后,加载控制器

    .state('app.user.customer.detail', {
    url: '/{id}',
    templateUrl: "assets/views/customerDetail.html",
    resolve: { loadMyService: ['$ocLazyLoad', '$injector', 
                    function($ocLazyLoad, $injector) {
            return $ocLazyLoad.load('assets/js/services/customer.js').then(
                        function() {                            
                            return $ocLazyLoad.load('assets/js/services/customerFirstService.js').then(function() {
    
                                var $serviceTest = $injector.get("CustomerFirstLoad");
                                $serviceTest.testLoad();
    
                                }).then(function(){
                                            return $ocLazyLoad.load(['assets/js/controllers/customerCtrl.js']);
                                  });
                            });
    
                     }]}
    

这是服务

'use strict';

app.factory('CustomerFirstLoad', ['$q', '$timeout', function Customers($q, $timeout) {
    var svc = {};

    svc.testLoad = function(){
        var deferrer = $q.defer(); 

        $timeout(function(){
            console.log("response");
            deferrer.resolve("response");
        }, 3000);
      return deferrer.promise;
  };

return svc;
}]);

一些建议?

4

1 回答 1

4

试试这个

.state('app.user.customer.detail', {
url: '/{id}',
templateUrl: "assets/views/customerDetail.html",
resolve: { loadMyService: ['$ocLazyLoad', '$injector', 
                function($ocLazyLoad, $injector) {
        return $ocLazyLoad.load('assets/js/services/customer.js').then(
                    function() {                            
                        return $ocLazyLoad.load('assets/js/services/customerFirstService.js').then(function() {

                            var $serviceTest = $injector.get("CustomerFirstLoad");
                            return $serviceTest.testLoad(); // <-- CHANGED HERE

                            }).then(function(){
                                        return $ocLazyLoad.load(['assets/js/controllers/customerCtrl.js']);
                              });
                        });

                 }]}

你需要回报承诺,因为$serviceTest.testLoad()这种方式直到完成$ocLazyLoad才会继续。$serviceTest.testLoad()

于 2015-09-21T07:44:01.370 回答