8

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.

raju
  • 4,859
  • 11
  • 54
  • 108

3 Answers3

13

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

this worked for me:

const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);
Steve
  • 1,138
  • 11
  • 19
8

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);
    }
}
SoFolichon
  • 71
  • 2
  • 8
ngLover
  • 3,716
  • 1
  • 17
  • 38
  • 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
4

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
  • 63
  • 7