Angular 2 And Controlling HTTP Request and Response

前端 未结 2 1141
無奈伤痛
無奈伤痛 2021-01-24 20:12

In Angular 2 I am trying to control http request/response to set/read some headers when sending request and getting response.

I just override HttpRequest like this, and

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 20:53

    You could implement it in a few ways: create base service class or provide custom xhr implementation:

    @Injectable()
    export class CustomBrowserXhr extends BrowserXhr {
      constructor() {}
      build(): any {
        let xhr:XMLHttpRequest = super.build();
        /*...add headers, listeners etc...*/
        return (xhr);
      }
    }
    
    bootstrap(AppComponent, [
      HTTP_PROVIDERS,
      provide(BrowserXhr, { useClass: CustomBrowserXhr })
    ]);
    

提交回复
热议问题