我有一个简单的场景 - 我希望使用拦截器初始化我的 http 调用,该拦截器将在 header 中添加一个值(某种 token )。
问题是 token 也是通过http接收的(它应该是第一个调用),但我不知道如何让所有其他调用等待它完成,然后再发出自己的调用...
.factory('sessionData', function () {
var currentToken = '[uninitialized-token]';
return {
getToken: function () {
return currentToken;
},
setAuthData: function (token) {
currentToken = token;
}
}
})
.factory('sessionInjector', ['sessionData', function (sessionData) {
var sessionInjector = {
request: function (config) {
console.log("sending with token: " + sessionData.getToken());
config.headers['x-header-sessionID'] = sessionData.getToken();
}
};
return sessionInjector;
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('sessionInjector');
}])
.run(['$http', 'configs', 'sessionData', function ($http, configs, sessionData) {
$http.get(configs.authApiUrl + 'login').then(function (ret) {
sessionData.setAuthData(ret);
console.log("successfully authenticated with token " + sessionData.getToken());
});
}])
.controller('TestCtrl', function($http){
$scope.p1 = 'Uninitialized';
$http.get('http://localhost/api/getData').then(function(ret){
$scope.p1 = ret;
});
});
问题是 TestCtrl
在 run
方法完成获取 token 之前发出 http 调用(导致 header 值具有[uninitialized-token] 在它的值中)。
如何让 Controller 等待“运行”异步方法完成?
最佳答案
$http 拦截器可用于在回调中返回 Promise。您可以使用它来拦截每个调用并延迟它,直到 promise 得到解决。
您应该了解 Promise 是如何发挥作用的。
示例:
myModule.factory('tokenPromise', function($http) {
return $http.get({url: 'myurl/token', bypassToken: true}).then(function(data) {
// This is when your token webservice return, deal with the response here
return data.token;
});
});
myModule.factory('myHttpInterceptor', function($q, tokenPromise) {
return {
'request': function(config) {
if (config.bypassToken) return config;
// This ensures the token promise is resolved before proceeding with the request.
return tokenPromise.then(function(token) {
config.headers['x-header-sessionID'] = token;
return config;
});
},
};
});
myModule.config(function($httpProvider) {
//wire the interceptor here
$httpProvider.interceptors.push('myHttpInterceptor');
})
关于javascript - AngularJS:如何保持在 'run' 方法直到完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859035/