簡體   English   中英

控制器內的角度解析

[英]Angular resolve within a controller

在我的全局/主控制器中,我加載了幾個ngResources。 如何在加載之前暫停執行其他任何操作? 與路由的resolve屬性相似。

// The "global" controller in which I perform one time on load actions.
app.controller('FrontendCtrl', function($scope, authService, sessionService) {

  // Here I check if the user has a cookie and if so fetch info from server to reinit session
  authService.updateUser();

  $scope.$session = sessionService;

});

// Auth service
app.factory('authService', function($q, Auth, Other, sessionService) {

    // Populate local user data from server - one query followed by a few subsequent ones - all are ngResources
    var updateUser = function() {
      Auth.profile(null, function(data) {
        if(data) {
          $q.all({
            foo: Other.foo({ user_id: data.id }),
            bar: Other.bar({ user_id: data.id }),
           })
          .then(function(results) {
            sessionService.user = _.merge(results, data);
          });
        }
      });
    };
});

// In my view - this doesn't work if there is a delay in loading the updateUser function
{{ $session.user.name }}

您需要利用回調才能讓服務首先填充會話值,這是適合您的代碼:

// Auth service
app.factory('authService', function($q, Auth, Other) {

    // Populate local user data from server - one query followed by a few subsequent ones - all are ngResources
    return {
      updateUser:  function(callback) {
        Auth.profile(null, function(data) {
          if(data) {
            $q.all({
              foo: Other.foo({ user_id: data.id }),
              bar: Other.bar({ user_id: data.id }),
             })
            .then(function(results) {
              //If sessionService is only an object in this case
              callback(sessionService);
            });
          }
        });
      };
    }

});

並在控制器中:

// The "global" controller in which I perform one time on load actions.
app.controller('FrontendCtrl', function($scope, authService) {

  // Here I check if the user has a cookie and if so fetch info from server to reinit session
  //Update: Now a callback to fetch session data
  authService.updateUser(function(data){
    $scope.$session = data;
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM