【问题标题】:Angular interceptor, run code after the outgoing request is finishedAngular 拦截器,在传出请求完成后运行代码
【发布时间】:2018-03-01 17:35:21
【问题描述】:

我有一个简单的拦截器,它检查传出请求是否针对特定端点类型,在本例中为 eventsfavoriteevents

这几乎可以按预期工作。它做错的一件事是this.dispatcher 在传出请求完成之前调度。

我怎样才能改变它,使传出请求首先运行,然后进行调度调用?

import {Injectable, Injector, Optional} from '@angular/core';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';

import {Observable} from 'rxjs/Observable';

import {AppConstants} from '@constants/app-constants.constant';
import {DispatcherService} from '@services/dispatcher.service';

@Injectable()

export class EventsInterceptor implements HttpInterceptor {

  constructor(private dispatcher: DispatcherService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const urls = [
      {requestType: 'PUT', snippet: '/events/'},
      {requestType: 'DELETE', snippet: '/events/'},
      {requestType: 'PUT', snippet: '/favoriteevents'},
      {requestType: 'DELETE', snippet: '/favoriteevents'}
    ];

    for (const url of urls) {

      if (req.method === url.requestType || url.requestType === null) {

        if (req.url.indexOf(url.snippet) !== -1) {
          this.dispatcher.dispatch({type: AppConstants.actions.refreshFavoriteEvents});
        }
      }
    }

    return next.handle(req);
  }
}

【问题讨论】:

    标签: angular typescript angular-http-interceptors angular-httpclient


    【解决方案1】:

    你可以试试

    ...
    return next.handle(req).pipe( tap( () => {
        if (someCondition) this.dispatcher.dispatch(...);
    }) );
    

    【讨论】:

    • 绝对精彩。
    猜你喜欢
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多