【问题标题】:Intercept all HTTP requests from angular2拦截来自 angular2 的所有 HTTP 请求
【发布时间】:2017-02-09 10:16:26
【问题描述】:

我正在寻找一种方法来拦截 angular 发出的所有 HTTP 请求并添加一些 headers。在angular2 RC5NgModule 之前)之前的版本中是这样的,例如:

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 相同,复制,因为如果你在{Provide: RequestOptions, useClass: BaseRequestOptions} 中使用BaseRequestOptions,一切正常,可以看到this example

【问题讨论】:

    标签: angular typescript angular2-http


    【解决方案1】:

    我发现您的代码中有两个错误

    • 你没有导入RequestMethod

    • 你必须在NgModule之前声明你的扩展类MyOptions 装饰师

    这样您的演示将看起来像 Plunker

    【讨论】:

    • RequestMethod 是一个细节,主要问题是类声明的顺序。完美更正,谢谢。尽管是愚蠢的错误很难识别,但看到您的回复毫无意义。
    【解决方案2】:

    你可以看看下面的 StackOverflow 问题,他们对此进行了深入讨论,

    What is httpinterceptor equivalent in angular2?

    Interceptors in Angular2

    【讨论】:

    • 好的,我已经看到了其中一些主题,这些问题和答案涵盖了以前的方法(角度以前的 RC 5),如 the beginning of the question 所示。但就我而言,问题出在当前版本的 angular (angular 2.0 final) 上。
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2011-06-14
    • 2023-03-19
    相关资源
    最近更新 更多