gpt4 book ai didi

来自 HTTP 拦截器的 Angular 4 HTTP 请求

转载 作者:可可西里 更新时间:2023-11-01 16:29:40 27 4
gpt4 key购买 nike

我正在尝试将 Http 更新为较新的 HttpClient

为了刷新 JWT,我扩展了 Http 类并覆盖了 request() 方法 ( https://stackoverflow.com/a/45750985/2735398 )。
现在我想对拦截器做同样的事情。

这是我现在拥有的拦截器:

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);
});
}
}

问题是我无法注入(inject) HttpClient,因为我得到一个错误:

Provider parse errors:
Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

通过扩展 Http,我可以调用 this.post(),因为我在 Http 实例本身中工作。但是对于拦截器,这是无法做到的。

如何在拦截器中发出 HTTP 请求?

最佳答案

您可以从 @angular/core 注入(inject) Injector 并在需要时获取依赖项:

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);
});
}
}

关于来自 HTTP 拦截器的 Angular 4 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46813190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com