我正在尝试在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。
答案 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
。