Angular 4-Observable.do()的回调未在拦截器中调用 [英] Angular 4 - Callback for Observable.do() does not get called in interceptor

查看:94
本文介绍了Angular 4-Observable.do()的回调未在拦截器中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试实现在请求进行时显示加载指示符的解决方案.从

Trying to implement solution for displaying a loading indicator when requests are in progress. Looking from this solution I implemented the interceptor with the service. All works fine, except the counter is not deceasing becase the .do() callback never gets executed (b is never printed in the console). Any thoughts on that? How to know if request has finished?

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.您可以这样做:

The do() is never fired because you have to return your new observable. you could do it like so:

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--;
  });
}
}

这篇关于Angular 4-Observable.do()的回调未在拦截器中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆