I am learning Angular6 Http and interceptors.
I have created an interceptor
@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);
}
}
This is working fine I get console.log whenever I hithttps://abcd.azure.net/api/v1/getPendinList
. What I am trying to acheive is that if I hit this url, I want to change this url into something else ,e.g. abcd.api.com/search
. So that my url fetch data from new endpoint.
Is this possible and how.
Yes, you can override URL with new HTTPREQUEST
or cloning. but you can't directly assign new URL because it's a constant/read-only property.
//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);
}
}
from:
https://stackoverflow.com/a/45735866/1778005
this worked for me:
const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
the problem with ngLover answer is that he over-write everything because he is creating new http request which will have null body
the correct answer is actually simpler
const newUrl = {url: 'new-url'};
req = Object.assign(req, newUrl);
that way only the url
property will be over-written and the remaining properties will not change including the body