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() 因为您必须 return 您的新可观察对象。你可以这样做:
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--;
});
}
}
尝试实现在请求进行时显示加载指示器的解决方案。从 .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() 因为您必须 return 您的新可观察对象。你可以这样做:
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--;
});
}
}