Search code examples
angularjsangular-ui-routeroclazyload

Resolve resource call before controller load with OcLazyLoad


I need to perform an http call to my webservice using a $resource provider. I'd like to resolve first the data coming from the http call, then inject this result in the controller. Thinking in terms of OcLazyLoad I just wrote this piece of code. In my mind it should:

  • First load service;
  • Make the http call;
  • When the promise is resolved, load the controller

    .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']);
                                  });
                            });
    
                     }]}
    

This is the service

'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;
}]);

Some advices?


Solution

  • Try this

    .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']);
                                  });
                            });
    
                     }]}
    

    You need to return the promise of $serviceTest.testLoad() becouse in this way $ocLazyLoad doesn't go on until $serviceTest.testLoad() finished.