我的angular应用程序分为4个模块,所有模块都需要用户详细信息,所以我从每个模块调用getUser方法。因此,当我的应用程序加载时,所有4个模块同时命中getUser应用程序接口,导致在服务器上产生4个get请求。我如何防止这种情况发生?我在getUser方法中使用了单例模式,所以一旦加载了我的用户,它就会简单地从一个对象为用户提供服务。但是,如果所有模块同时为用户请求,这并不能解决问题。
我的代码如下所示
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;
}
发布于 2017-02-16 20:45:49
通过将当前请求存储在一个变量中,对UserService.get
的调用将返回相同的请求承诺。
然后,当promise解析时,它将解析到所有模块。
angular.module('app').service('UserService', function ($http) {
var self = this;
var getRequestCache;
/**
* Will get the current logged in user
* @return user
*/
this.get = function () {
if (getRequestCache) {
return getRequestCache;
}
getRequestCache = $http({
url: '/api/user',
method: 'GET',
cache: false
}).then(function (response) {
// clear request cache when request is done so that a new request can be called next time
getRequestCache = undefined;
return response.data;
});
return getRequestCache;
};
});
发布于 2017-02-16 20:51:39
您正在使用ui-router
进行路由。然后,您可以在登录到页面时使用它来解析用户。
在您的路由配置中:
$stateProvider
.state('myPage', {
url: '/myPage',
templateUrl: 'myPage.html',
controller: 'myCtrl',
resolve: {
userDetails: ['UserService', function(UserService) {
return UserService.getUserDetails();
}],
}
})
在你的控制器中
angular.module('myModule')
.controller('myCtrl', ['userDetails', function(userDetails) {
console.log(userDetails);
}];
这将在加载页面的同时加载用户详细信息。
发布于 2017-02-16 22:03:52
我通过使用defer对象作为全局对象解决了这个问题,这样它只需要初始化一次。
https://stackoverflow.com/questions/42274199
复制相似问题