how to change http req url using angular 6 interceptor

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

this worked for me:

const dupReq = req.clone({ url: 'mynewurl.com' });
return next.handle(dupReq);

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);
    }
}

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

Tags:

Angular