gpt4 book ai didi

angular4-httpclient - 仅针对特定服务的拦截器

转载 作者:行者123 更新时间:2023-12-04 08:05:27 24 4
gpt4 key购买 nike

我的应用中有几项服务指向不同的 API URL。现在我需要为这些服务中的每一个设置不同的 header 。我现在的问题是关于 Angular 4 中的新拦截器。是否有可能为特定服务设置一个拦截器?那么每个服务都有其特定的拦截器吗?

希望你们能得到我的问题。

最佳答案

实际上有一种方法可以为特定服务提供拦截器。注意重点,因为它实际上不是 HttpInterceptor 的实现。界面。
TL:博士 - 跳转到底部的示例。HttpClient实际上只是通过所有可能的方法将输入转换为一个名为 HttpRequest 的结构。 ,然后将其传递给 HttpHandler执行。顾名思义,它负责处理 HTTP 请求。
其中HttpHandler你会发现的实现,例如 HttpInterceptingHandler (运行拦截器链)或 HttpXhrBackend (通过 HttpBackend 类继承,此处理程序是最后一个,因为它实际发送 XHR 请求)。如果您查看 the source code of the former class ,您会看到它实际上取决于后者(间接地,在 HttpBackend token 下,HttpXhrBackend 作为默认实现提供)。所以就像拦截器一样,Angular 通过 DI 链接处理程序,其中最后一个是执行请求的后端。
您可以做的是向这个处理程序链添加另一个处理程序,理想情况下作为第一个处理程序。为此,您必须定义一个扩展 HttpHandler 的类。 , 注入(inject) HttpHandler 的第一个实现(首先我指的是实现,它在 HttpHandler token 下提供)并且只是在 handle 中调用完成后的方法。
最后,由于 HTTP 客户端是一个 Angular 服务,它可能会在更多服务之间共享,因此您需要创建自己的实例来避免这种情况。 HttpClient 构造函数需要 HttpHandler例如,您在其中传递自己的实现。
请参阅我在此类处理程序中处理身份验证的简单示例:

@Injectable()
export class AuthHandler extends HttpHandler {
constructor(
private readonly auth: AuthService, // custom service providing the auth token
private readonly next: HttpHandler // injects the "default" handler -> HttpInterceptingHandler
) {
super();
}

/** @override */ handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
// do whatever you need on the request
// because of immutability cloning is required
const clone = req.clone({
setHeaders: { 'Authorization': 'Bearer ' + auth.getToken() }
});
// pass the request to the next handler, eventually ending up in HttpXhrBackend
return this.next.handle(clone);
}
}
以及该处理程序在该特定服务中的使用:
export class HeroService {
protected readonly http: HttpClient;

constructor(auth: AuthHandler) {
// create your own instance with you custom handler
this.http = new HttpClient(auth);
}

async getHero(id: string): Hero {
// every request made through such client goes to the handler for processing
await this.http.get<Hero>(`/api/heroes/${id}`).toPromise();
}
}
这段代码在 Angular 8 上为我工作。
我希望这可以帮助其他迷失的灵魂寻找解决方案。

关于angular4-httpclient - 仅针对特定服务的拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130770/

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