如何使用Angular 6拦截器更改http req url [英] how to change http req url using angular 6 interceptor

查看:106
本文介绍了如何使用Angular 6拦截器更改http req url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular6 Http和拦截器.

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

这很好用,只要我按 https://abcd.azure.net/api/v1/getPendinList ,我都会获得console.log.我想要达到的目的是,如果我点击此网址,我想将此网址更改为其他内容,例如 abcd.api.com/search .这样我的url就会从新端点获取数据.

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.

这有可能吗?

推荐答案

是的,您可以使用新的 HTTPREQUEST 或克隆覆盖URL.但是您不能直接分配新的URL,因为它是一个常量/只读属性.

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

这篇关于如何使用Angular 6拦截器更改http req url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆