Jan*_*tze 3 http jwt angular-http-interceptors angular
我正在尝试更新Http
到较新的HttpClient
.
对于 JWT 刷新,我扩展了Http
类并覆盖了request()
方法(/sf/answers/3202568981/)。
现在我想对拦截器做同样的事情。
这是我现在拥有的拦截器:
export class JwtRefreshInterceptor implements HttpInterceptor {
public constructor(
private httpClient: HttpClient,
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((error: HttpErrorResponse) => {
if (error.status === 401) {
return this.httpClient.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => {
// get token from response.
// put token in localstorage.
// add token to the request.
// Do the request again with the new token.
return next.handle(request);
});
}
return Observable.throw(error);
});
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我无法注入,HttpClient
因为出现错误:
Provider parse errors:
Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
Run Code Online (Sandbox Code Playgroud)
通过扩展,Http
我可以直接调用,this.post()
因为我在Http
实例本身中工作。但是对于拦截器,这是无法做到的。
如何在拦截器中发出 HTTP 请求?
你可以注入Injector
的@angular/core
并在需要时获得依赖性:
export class JwtRefreshInterceptor implements HttpInterceptor {
constructor(private injector: Injector) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((error: HttpErrorResponse) => {
if (error.status === 401) {
const http = this.injector.get(HttpClient);
return http.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => {
// get token from response.
// put token in localstorage.
// add token to the request.
// Do the request again with the new token.
return next.handle(request);
});
}
return Observable.throw(error);
});
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3488 次 |
最近记录: |