2014-02-19 50 views
1

所以這有點複雜,但我會努力進入它,盡我所能。在我config.js,我有:如何鏈接來自不同控制器/地方的AngularJS承諾?

.run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $location, UserService, CompanyService) { 
    $rootScope.globals = {}; 

    $rootScope.$on('login', function(event, data) { 
    $rootScope.api_key = data.api_key; 
    CompanyService.get(data.user.company_id); 
    }); 

    UserService.checkAuth().then(function(response) { 
    if(response.data.user) { 
     // Logged in user 
     $rootScope.$broadcast('login', response.data); 
    } else { 
     UserService.logout(); 
    } 
    }); 
}]); 

基本上會檢查用戶是否登錄如果他是,我們發現他屬於哪個用戶與CompanyService到:

angular.module('mean').service('CompanyService', ['$http', '$rootScope', function($http, $rootScope) { 
    var company = this; 
    company.company_data = {} 

    company.getCompany = function() { 
    return company.company_data; 
    } 

    company.get = function (company_id) { 
    return $http({ 
     url: '/api/v1/company/' + company_id, 
     method: 'GET', 
     headers: { 
     api_key: $rootScope.api_key 
     } 
    }).success(function(response) { 
     if(response.status === 'ok') { 
     company.company_data = response.company; 
     } 
    }); 
    }; 
}]); 

後來在我的代碼,我有依靠單CompanyService做一個API呼叫的呼叫:

$scope.index = function() { 
    LocationService.get(CompanyService.getCompany()._id, $routeParams.location_parent_id).then(function(response) { 
     if(response.data.status === 'ok') { 
     $scope.locations = $scope.locations.concat(response.data.locations); 
     } 
    }); 
    } 

如果我刷新頁面,但是,有時候這種調用得到的exe在我們將數據放入CompanyService單身人士之前先取消。我如何使用promise來確保LocationService直到在CompanyService singleton中有數據之後纔會發生?

回答

1

做到這一點的一種方法是不改變你現有的代碼太多會創建一個promise有數據時履行。請注意,此代碼不處理錯誤,這樣還必須添加...

angular.module('mean').service('CompanyService', 
     ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) { 
    var company = this; 
    company.company_data = {} 

    var initializedDeferred = $q.defer; 
    company.initialized = initializedDeferred.promise; 

    company.getCompany = function() { 
     return company.company_data; 
    } 

    company.get = function (company_id) { 
     return $http({ 
      url: '/api/v1/company/' + company_id, 
      method: 'GET', 
      headers: { 
       api_key: $rootScope.api_key 
      } 
     }).success(function (response) { 
      if (response.status === 'ok') { 
       company.company_data = response.company; 
       initializedDeferred.resolve(); // reject promise on error? 
      } 
     }); 
    }; 
}]); 

$scope.index = function() { 
    CompanyService.initialized.then(function() { 
     LocationService.get(CompanyService.getCompany()._id, 
      $routeParams.location_parent_id).then(function (response) { 
      if (response.data.status === 'ok') { 
       $scope.locations = $scope.locations 
         .concat(response.data.locations); 
      } 
     }); 
    }); 
} 
+0

我越來越:'CompanyService.initialized是undefined' – Shamoon