由于我使用Oauth2来保护我的API,如果先前的访问令牌已过期,则需要在任何HTTP请求之前获取新的访问令牌。
直到现在,我很少使用事件监听器。
这是我目前所做的(请告诉我是否正确):
ApplicationController.js:
app.controller('ApplicationController', function($rootScope, $scope, $localStorage, AuthService){
// Listening event apiRequested
$scope.$on('event:apiRequested', function(e) {
AuthService.token();
// Restore the access_token in case it has changed
access_token = $localStorage.getObject('access_token');
});
})
UserController.js :
$rootScope.$broadcast('event:apiRequested');
// Get Users around
return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
return response;
});
首先,我不确定的是...如果事件已经完全执行,$http是否会被处理?
所以,既然我不确定,我考虑添加一个回调函数。
下面是我的想法:
$rootScope.$broadcast('event:apiRequested', function(response){
if(response){
// Get Users around
return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
return response;
});
}
});
请问是否有可能这样做,或者我应该使用其他方法来处理这种情况,与事件监听器不同。