Hular与Angular 2

时间:2016-03-18 16:23:00

标签: angular

我正在尝试在Angular 2中为Http使用替代类。

我想要在构造函数

中设置CustomHttp类设置默认选项
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");
    }
}

我在bootstrapping时尝试了各种选项,因为我希望这个重载对我的app来说是全局的。

我试过了:

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

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

我也尝试过:

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

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

我该怎么办?

我正在使用beta 9。

1 个答案:

答案 0 :(得分:2)

您需要使用工厂使用RequestOptions而不是BaseRequestOptions对其进行配置:

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

HTTP_PROVIDERS仅提供RequestOptions而不是BaseRequestOptions

如果要通过定义自定义请求选项的子类来定义自定义请求选项,则应使用

BaseRequestOptions