我正在尝试使用 Angular5HttpInterceptor
在所有 HTTP 请求中注入 Authorization 标头来实现。
我依赖第三方库(ADAL,这里称为AuthService
),它公开了一种acquireToken()
方法来获取用于承载授权的令牌。
问题是aquireToken()
返回一个可观察的,我必须订阅才能获得我需要的真实字符串。
因此,我的代码从不注入标头,我想是因为在返回任何值next.handle()
之前执行。acquireToken()
如何确保仅在检索到令牌后才调用下一个处理程序?
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {AuthService} from 'mylibrary';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headers = req.headers || new HttpHeaders();
this.auth.acquireToken(req.url)
.subscribe((token: string) => {
headers = headers.append('Authorization', 'Bearer ' + token);
});
return next.handle(req.clone({ headers: headers }));
}
}