我正在寻找一种方法来拦截角度所做的所有HTTP请求,并添加一些标头。在angular2 RC5
之前的版本(NgModule
之前)是这样的,例如:
class MyOptions extends BaseRequestOptions {
Authorization: string = 'Bearer ' + localStorage.getItem('tokenName');
}
bootstrap(AppComponent,
[HTTP_PROVIDERS,
{ provide: RequestOptions, useClass: MyOptions },
appRouterProviders,
disableDeprecatedForms(),
provideForms(),
]).catch(err => console.error(err));
我目前的版本为2.0 final
,而research on how this would be implemented in this version与此类似:
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
providers: [
{ provide: RequestOptions, useClass: MyOptions }
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
@Injectable()
export class MyOptions extends RequestOptions {
constructor() { super({method: RequestMethod.Get, headers: new Headers()}); }
}
它显示以下错误:TypeError: Can not read property 'merge' of null
。可以看出this example。
注意:
MyOptions
的实施与复制的BaseRequestOptions
相同,因为如果您在BaseRequestOptions
中使用{Provide: RequestOptions, useClass: BaseRequestOptions}
,一切正常,可以看到{{ 3}}
答案 0 :(得分:2)
答案 1 :(得分:0)