Angular 2-在每个Http请求之前注入授权令牌 [英] Angular 2 - Inject authorization token before each Http request
本文介绍了Angular 2-在每个Http请求之前注入授权令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在发送每个HTTP请求之前,我需要检查我的令牌是否未过期.我正在尝试使用Http Interceptor进行注入,例如:
I need to check that my token is not expired before I send every HTTP request. I'm trying to make injection using Http Interceptor like this:
class HttpInterceptor extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
super(backend, defaultOptions);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
const keycloak$: Observable = KeycloakService.updateToken();
return keycloak$.map((options) => {
return super.get(url, this.getRequestOptionArgs(options));
});
// -> Observable<Observable<Response>>
}
getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
}
如何实现可观察的依赖关系. KeycloakService.updateToken()
返回另一个Observable
,因此我需要等待响应,然后添加Authorization标头.我将不胜感激.
How I can implement Observable dependency. KeycloakService.updateToken()
returns another Observable
, so I need to wait for response and then add Authorization header. I will be grateful for any tips.
推荐答案
使用switchMap
等待super.get()
返回的可观察对象解析,然后发出响应
Use switchMap
to wait for the observable returned by super.get()
to resolve before emitting the response
替换
return keycloak$.map((options) => {
return super.get(url, this.getRequestOptionArgs(options));
});
使用
return keycloak$.switchMap(
options => super.get(url, this.getRequestOptionArgs(options))
);
我也会更改:
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
使用:
if(!options) options = new RequestOptions();
if(!options.headers) options.headers = new Headers();
为了捕获undefined
和null
选项
这篇关于Angular 2-在每个Http请求之前注入授权令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文