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.
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response.
To implement an interceptor, you'll want to create a class that's injectable and that implements HttpInterceptor. The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent. req is the request object itself and is of type HTTP Request.
Create a class AppHttpInterceptor which implements HttpInterceptor Interface. Then create an Intercept method that takes HttpRequest and HttpHandler as the argument. In the method body, you can modify the HttpRequest object. Once done, you can call the HttpHandler.
So how can I add multiple interceptors? Http doesn't allow to have more than one custom implementation. But as @estus mentioned the Angular team has added a new HttpClient service recently (release 4.3) which supports multiple interceptors concept. You don't need to extend the HttpClient as you do with the old Http .
from: https://stackoverflow.com/a/45735866/1778005
this worked for me:
const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With