我有2个api,它们具有不同的起始url,并且都带有不同的标头。所以我想根据特定的URL请求设置标题。
目前,即使条件始终为true,即使这两个条件都不向122.22.332.3/anylink发出请求,
我应该把return next.handle(req);
放在哪里,因为如果我不运行它,它应该放在第一个,然后第二个。
export class InterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
if (req.url.indexOf('/maxim/public') === -1) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
}
if (req.url.indexOf('122.22.332.3/') === -1) {
console.log("x");
req = req.clone({
setHeaders: {
Authorization: `Bearer dsfdsfdsfdsfsdxcsdfw23dsfdsf`
}
});
return next.handle(req);
}
}
}
答案 0 :(得分:0)
目前,即使两个条件始终为真, 不向122.22.332.3/anylink发出请求的组件
您的问题不是return语句,而是两个条件都适用且URL不同的事实。您为什么不否定条件?
if (req.url.startsWith('/maxim/public')) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
}
if (req.url.startsWith('122.22.332.3/')) {
console.log("x");
req = req.clone({
setHeaders: {
Authorization: `Bearer dsfdsfdsfdsfsdxcsdfw23dsfdsf`
}
});
return next.handle(req);
}
}