我正在寻找一种方法来拦截 Angular 发出的所有 HTTP 请求并添加一些 header 。在 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:无法读取 null 的属性“merge”
。可以看出this example .
Note: The implementation of
MyOptions
is the same asBaseRequestOptions
, copied, because if you useBaseRequestOptions
in{Provide: RequestOptions, useClass: BaseRequestOptions}
, everything works, as can be seen this example.
最佳答案
关于angular - 拦截来自 Angular2 的所有 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39798231/