Angular 2 And Controlling HTTP Request and Response

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 it is working for me :

@Injectable()
export class HttpRequest extends RequestOptions {
    constructor() {
         super({
             method: RequestMethod.Get,
             headers: new Headers({
                'X-Some-Header': 'some-content'})
        });
    }
}

But for overriding Response I have problem :

@Injectable()
export class HttpResponse extends Response {
    constructor(responseOptions: ResponseOptions) {
        super(responseOptions);
        console.log("RESPONSE IS CREATED!!!!!!!");
    }
}

The constructor never being called and here it is the bootstrap:

bootstrap(AppComponent,
    [   ROUTER_PROVIDERS
        ,HTTP_PROVIDERS
        ,provide(RequestOptions, {useClass: HttpRequest})
        ,provide(Response, {useClass: HttpResponse})
    ]);

The reason for overriding the response is to read some response headers and control for 404-Not Page Found globally and ….

Thanks,

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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 <any>(xhr);
  }
}

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

Jason
Guest

You can’t override Response I remember seeing that it is being created using new Response in one of the related Http classes instead of requesting it from the injector, which is reasonable because Response needs to be a dufferent instance for each request.