簡體   English   中英

Angular 4-Observable.do()的回調未在攔截器中調用

[英]Angular 4 - Callback for Observable.do() does not get called in interceptor

嘗試實現在請求進行時顯示加載指示器的解決方案。 解決方案來看,我使用該服務實現了攔截器。 一切工作正常,除非計數器不會減少,否則不會執行.do()回調(從不在控制台中打印b )。 有什么想法嗎? 如何知道請求是否已完成?

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

import { LoadingIndicatorService } from './loading-indicator.service';

@Injectable()
export class LoadingIndicatorInterceptor implements HttpInterceptor {
    constructor(private loadingIndicatorService: LoadingIndicatorService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.loadingIndicatorService.requestsCount++;

      const handleObs: Observable<HttpEvent<any>> = next.handle(req);

      console.log('a');
      handleObs.do(() => {
        console.log('b');
        this.loadingIndicatorService.requestsCount--;
      });

      return handleObs;
    }
}

永遠不會觸發do(),因為您必須返回新的Observable。 您可以這樣做:

export class LoadingIndicatorInterceptor implements HttpInterceptor {
constructor(private loadingIndicatorService: LoadingIndicatorService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  this.loadingIndicatorService.requestsCount++;

  const handleObs: Observable<HttpEvent<any>> = next.handle(req);

  console.log('a');
  return handleObs.do(() => {
    console.log('b');
    this.loadingIndicatorService.requestsCount--;
  });
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM