AngularJS Load controllers only when parent controller finishes async call

天涯浪子 提交于 2019-12-05 06:32:59
DavidC

Edited based on comments below

The idea is to block off the view with an ng-if until the api call has returned:

// Session service
 this.init = function(){
      if (!this.initDone){
          var s = this;
          var deferred = $q.defer();
          gapi.client.myapi.app.init().execute(function(resp){
              deferred.resolve(resp);
              s.initDone = true;
          });
          return deferred.promise;
      }
 }




// MainController.js :
 $scope.initDone = false;
 SessionService.init().then(function(
     $scope.initDone = SessionService.getInitDone();
  });


// index.html: 
<div ng-if="initDone"> 
    <div id="view" ng-view> </div>
</div> 

Old answer: Could you move the async call to Google to a service and have that service return a promise

     myApp.service('DataService', ['$rootScope', '$http', function ($rootScope, $http) {

     var promise = $http.get("http://google.com/theservice").success(function (data) {
             ......
      });
      this.promise = promise

In your routing setup then have a resolve which will wait for the only load the controller after the call to the Google service has returned

    when('/example', {templateUrl: 'partials/example.html', 
                   controller: 'ExampleCtrl', 
         resolve: {
            'MyServiceData': function (DataService) {
                return DataService.promise;
            }
        }}).

Edit: Have a look here how to return a promise for an api call https://stackoverflow.com/a/16117041/514463

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!