我创建了一个实现HttpInterceptor的自定义身份验证拦截器。我将使用httpClient为每个请求添加标题。 现在我几乎没有需要添加身份验证标头的请求。
以下是我的自定义拦截器的代码供参考
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private franchiserService: FranchiserService,
private currentMerchantService: CurrentMerchantService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
console.log('Request Intercepted');
const franchiserKey = this.franchiserService.franchiser.apiKey;
const merchantKey = this.currentMerchantService.merchant.apiKey;
const authReq = req.clone({
headers: req.headers.append('franchiserKey', franchiserKey).append('merchantKey', merchantKey),
url: environment.origin + req.url
});
return next.handle(authReq);
}
}
我如何实现可以同时执行这两者的自定义拦截器?
答案 0 :(得分:1)
您可以通过在Angular中添加自己的http处理程序类型 (在角度文档中检查处理程序类型https://angular.io/api/common/http/HttpHandler) 来绕过Angular中的全局auth标头不需要截获的服务
import { HttpClient, HttpBackend } from @angular/common/http;
constructor(private http: HttpClient, private handler: httpBackend ) {
this.http = new HttpClient(handler); // provide handler of type HttpBackend }
添加HttpBackend类型的处理程序将通过传递所有其他处理程序并移动到最后一个处理程序。角度中的Auth拦截通常以添加auth拦截器的顺序发生,最后以HttpBackend结束。像这样直接添加它会跳过所有拦截