Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change http req url using angular 6 interceptor

Tags:

angular

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.

like image 507
raju Avatar asked Jun 14 '18 11:06

raju


People also ask

What is the use of HTTP interceptor in angular 6?

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.

When implementing an HTTP interceptor which method must be provided?

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.

How do you give the HTTP interceptor?

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.

Can I have multiple HTTP interceptors in angular?

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 .


Video Answer


1 Answers

from: https://stackoverflow.com/a/45735866/1778005

this worked for me:

const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
like image 112
Steve Avatar answered Oct 07 '22 12:10

Steve