Angular拦截器,在传出请求完成后运行代码

时间:2018-03-01 09:23:34

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

我有一个简单的拦截器,用于检查传出请求是否属于特定端点类型,在本例中为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);
  }
}

1 个答案:

答案 0 :(得分:3)

您可以尝试类似

的内容
rowwise()