17

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.

ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
raju
  • 6,448
  • 24
  • 80
  • 163

3 Answers3

26

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

this worked for me:

const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
Steve
  • 1,326
  • 14
  • 21
15

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);
    }
}
DuGabiche
  • 93
  • 2
  • 8
ngLover
  • 4,439
  • 3
  • 20
  • 42
  • It is working, just one more query, how can I convert POST to GET in http interceptor – raju Jun 18 '18 at 03:37
  • to change requestMethod you need to as follows const changeReqMethod = request.clone({ url: reqiest.url, method: "get" }); return next.handle(changeReqMethod); – Sandeep May 17 '20 at 19:15
5

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

Robert
  • 83
  • 1
  • 8