我正在学习Angular6 Http和拦截器。
我创建了一个拦截器
@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log(req);
if(req.url == 'https://abcd.azure.net/api/v1/getPendinList') {
// return Observable.empty();
console.log('hello')
}
const dupReq = req.clone({
headers: req.headers.set('Consumer-Secret', 'some sample key')
});
return next.handle(dupReq);
}
}
Run Code Online (Sandbox Code Playgroud)
每当我点击时,我都会获得console.log,这很好https://abcd.azure.net/api/v1/getPendinList。我要尝试实现的是,如果我点击此URL,我想将此URL更改为其他名称,例如abcd.api.com/search。这样我的url从新端点获取数据。
这可能吗?
来自:https : //stackoverflow.com/a/45735866/1778005
这为我工作:
const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用new HTTPREQUEST或clone 覆盖URL 。但是您不能直接分配新的URL,因为它是一个常量/只读属性。
//Added these lines
//const httpRequest = new HttpRequest(<any>req.method, 'abcd.api.com/search');
//req = Object.assign(req, httpRequest);
@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log(req);
const httpRequest = new HttpRequest(<any>req.method,'abcd.api.com/search');
req = Object.assign(req, httpRequest);
if(req.url == 'https://abcd.azure.net/api/v1/getPendinList') {
// return Observable.empty();
console.log('hello')
}
const dupReq = req.clone({
headers: req.headers.set('Consumer-Secret', 'some sample key')
});
return next.handle(dupReq);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
ngLover 答案的问题是他覆盖了所有内容,因为他正在创建新的 http 请求,该请求的正文将为 null 正确的答案实际上更简单
const newUrl = {url: 'new-url'};
req = Object.assign(req, newUrl);
Run Code Online (Sandbox Code Playgroud)
这样只有url属性会被覆盖,其余属性(包括主体)不会改变