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中有數據之後纔會發生?
我越來越:'CompanyService.initialized是undefined' – Shamoon