拦截来自 angular2 的所有 HTTP 请求
Intercept all HTTP requests from angular2
我正在寻找一种方法来拦截 angular 发出的所有 HTTP 请求并添加一些 headers。在 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.
Note: The implementation of MyOptions
is the same as BaseRequestOptions
, copied, because if you use BaseRequestOptions
in {Provide: RequestOptions, useClass: BaseRequestOptions}
, everything works, as can be seen this example.
你可以看看下面的 Whosebug 问题,他们对此有深入的讨论,
我看到你的代码中有两个错误
您没有导入 RequestMethod
您必须在 NgModule
之前声明您的扩展 class MyOptions
装饰器
这样您的演示将看起来像 Plunker
我正在寻找一种方法来拦截 angular 发出的所有 HTTP 请求并添加一些 headers。在 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.
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.
你可以看看下面的 Whosebug 问题,他们对此有深入的讨论,
我看到你的代码中有两个错误
您没有导入
RequestMethod
您必须在
NgModule
之前声明您的扩展 classMyOptions
装饰器
这样您的演示将看起来像 Plunker