由于我已经开始使用angular2,我已经设置了我的服务来返回T的Observable.在服务中我会有map()调用,使用这些服务的组件只会使用subscribe()来等待响应.对于这些简单的场景我真的不需要深入研究rxjs所以一切都还可以.
我现在想要实现以下目标:我正在使用Oauth2身份验证和刷新令牌.我想构建一个所有其他服务都将使用的api服务,并在返回401错误时透明地处理刷新令牌.因此,在401的情况下,我首先从OAuth2端点获取新令牌,然后使用新令牌重试我的请求.下面的代码工作正常,承诺:
request(url: string, request: RequestOptionsArgs): Promise<Response> {
var me = this;
request.headers = request.headers || new Headers();
var isSecureCall: boolean = true; //url.toLowerCase().startsWith('https://');
if (isSecureCall === true) {
me.authService.setAuthorizationHeader(request.headers);
}
request.headers.append('Content-Type', 'application/json');
request.headers.append('Accept', 'application/json');
return this.http.request(url, request).toPromise()
.catch(initialError => {
if (initialError && initialError.status === 401 && isSecureCall === true) {
// token might be expired, try to refresh token.
return me.authService.refreshAuthentication().then((authenticationResult:AuthenticationResult) => {
if (authenticationResult.IsAuthenticated == true) {
// retry with new token
me.authService.setAuthorizationHeader(request.headers);
return this.http.request(url, request).toPromise();
} …Run Code Online (Sandbox Code Playgroud)