【问题标题】:Angular2: Subscribe to all HTTP requestsAngular2:订阅所有 HTTP 请求
【发布时间】:2016-12-08 01:49:11
【问题描述】:

我正在使用 Angular2 构建一个 webapp。

Angular2每次发出HTTP请求时是否可以执行一个函数?

这将用于检查 JWT 令牌是否需要刷新。

谢谢!

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用自定义 Http 类,该类提供组件或其他服务可以订阅的可观察对象,并在每次发出请求时发出事件

    @Injectable() 
    class NotifyingHttp extends Http {
      requestSent:Subject = new Subject();
      requestCompleted:Subject = new Subject();
      constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions) {
        super(_backend, _defaultOptions);
      }
    
      get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
        this.requestSent.next(url);
        return super.get(newUrl, options)
        .finally(response => this.requestCompleted.next(url));
      }
    
      post(...)
      ...
    }
    

    每个方法都需要以这种方式覆盖(get、post、...)

    您可以创建一个共享模块,然后通过将其添加到 AppModule 的导入来激活该模块:

    @NgModule({
      imports: [HttpModule],
      export: [HttpModule],
      providers: [
       {provide: ConnectionBackend: useClass XhrBackend},
       {provide: Http, useClass: NotifyingHttp}]
    })
    export class NotifyingHttpModule {}
    
    @NgModule({
      imports: [BrowserModule, NotifyingHttpModule],
      declarations: [AppModule],
      bootstrap: [AppModule]
    })
    export class AppModule {}
    

    另见Angular2 : The responses to HTTP get requests are being cached in IE

    【讨论】:

    • 你需要使用工厂。扩展 Http Still 会导致 Angular 调用 Http 构造函数,而不是自定义类构造函数 (related to this)。所以你需要使用工厂并自己创建它。由于 ConnectionBackend 是一个接口(没有该令牌的提供者),因此您需要为工厂使用 XHRBackend。
    • 这也许可以解释为什么我必须添加提供程序 {provide: ConnectionBackend: useClass XhrBackend},但应该这样做(根据我最近在 plunker 中进行的测试)
    猜你喜欢
    • 2019-07-14
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2017-02-09
    • 2015-11-12
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多