Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative class provider for Http with Angular 2

Tags:

angular

I am trying to use an alternative class for Http in Angular 2.

I want to do so to have a CustomHttp class setting default options in constructor

import {Injectable} from 'angular2/core';
import {Http, RequestOptions, ConnectionBackend} from 'angular2/http';

@Injectable()
export class CustomHttp extends Http {
    constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions) {
        super(_backend, _defaultOptions);
        let jwtHeader = localStorage.getItem('jwt');
        if (jwtHeader != null) {
            this._defaultOptions.headers.append('Authorization', jwtHeader);
        }
        console.log("Pouet CustomHttp");
    }
}

I tried various options when bootstrapping, as I want this overload to be global to my app.

I tried :

bootstrap(AppComponent, 
    [HTTP_PROVIDERS,
        ROUTER_PROVIDERS,
        provide(Http, {useClass: CustomHttp,deps: [XHRBackend, BaseRequestOptions]})
    ]);

it raises :

browser_adapter.ts:73 EXCEPTION: No provider for ConnectionBackend! (TAPComponent -> SensService -> Http -> ConnectionBackend)

I also tried :

bootstrap(AppComponent, 
    [HTTP_PROVIDERS,
        ROUTER_PROVIDERS,
            provide(Http, {useFactory:
                function(backend, defaultOptions) {
                  return new CustomHttp(backend, defaultOptions);
                },
                deps: [XHRBackend, BaseRequestOptions]})
    ]);

it raises :

browser_adapter.ts:73 EXCEPTION: No provider for BaseRequestOptions! (TAPComponent -> SensService -> Http -> BaseRequestOptions)

What should I do ?

I am using beta 9.

like image 346
Ludovic Pénet Avatar asked Apr 10 '26 14:04

Ludovic Pénet


1 Answers

You need to use a factory to configure it with RequestOptions instead of BaseRequestOptions:

bootstrap(AppComponent, [HTTP_PROVIDERS,
  new Provider(Http, {
    useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
    deps: [XHRBackend, RequestOptions]
  })
]);

HTTP_PROVIDERS only provides RequestOptions not BaseRequestOptions.

BaseRequestOptions should be used if you want to define custom request options by defining a sub class of it.

like image 98
Thierry Templier Avatar answered Apr 12 '26 12:04

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!