问题
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;
}
}
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.
回答1:
Use switchMap
to wait for the observable returned by super.get()
to resolve before emitting the response
Replace
return keycloak$.map((options) => {
return super.get(url, this.getRequestOptionArgs(options));
});
With
return keycloak$.switchMap(
options => super.get(url, this.getRequestOptionArgs(options))
);
Examples
I would also change:
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
With:
if(!options) options = new RequestOptions();
if(!options.headers) options.headers = new Headers();
In order to catch undefined
as well as null
options
来源:https://stackoverflow.com/questions/39373645/angular-2-inject-authorization-token-before-each-http-request