My angular application is divided into 4 modules and all modules require user details so I am calling getUser method from each of the module. So when my application loads all 4 modules hit the getUser API simultaneously resulting in 4 get requests on server. How can I prevent this ? I am using singleton pattern in my getUser method so once my user gets loaded it will simply serve the user from an object. But that does not solves the problem if all modules request for the user simultaneously.
My code looks like this
getUser() {
let defer = this.q.defer();
if (!this.user) {
this.http.get(`${this.config.apiHost}users`)
.success(result => {
this.user = result;
this.rootScope.$broadcast('userFound', this.user);
defer.resolve(this.user);
})
.error(err => defer.reject(err))
}
else {
defer.resolve(this.user);
this.rootScope.$broadcast('userFound', this.user);
}
return defer.promise;
}