Attempting to explain in as much detail as possible, the configuration file config.js
contains the following code snippet:
.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) {
// User is logged in
$rootScope.$broadcast('login', response.data);
} else {
UserService.logout();
}
});
}]);
This section primarily focuses on checking whether a user is currently logged in. If they are, we proceed to identify their corresponding company using the 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;
}
});
};
}]);
Further along in the code, there's an instance where a particular function relies on the singleton CompanyService
for making an API call:
$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);
}
});
}
A challenge arises when, upon refreshing the page, this specific call sometimes occurs prior to populating data into the CompanyService
singleton. How can promises be effectively utilized to ensure that the LocationService
operation is delayed until after the necessary data is available within the CompanyService
singleton?