nic*_*wdy 0 rxjs angular-http-interceptors angular angular5
我在 Angular 5 中使用了带有 HttpInterceptor 的拦截器,并且我在使用 rxjs 时遇到了问题,其中我的所有 http 请求都重复了。
import { Router } from '@angular/router';
import { Injectable, ApplicationRef } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
import { NgxSpinnerService } from 'ngx-spinner';
import { ErrorHandlingService } from '../../service/error-handling.service';
@Injectable()
export class ApiRequestInterceptor implements HttpInterceptor {
private count: number = 0;
constructor(
private readonly spinner: NgxSpinnerService,
private readonly router: Router,
private readonly errorHandling: ErrorHandlingService,
private readonly applicationRef: ApplicationRef) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.count++;
if (this.count === 1) {
this.spinner.show();
}
return next.handle(req)
.catch((err: any) => {
this.count--;
return Observable.throw(err);
}).do(event => {
if (event instanceof HttpResponse) {
this.count--;
if (this.count === 0) this.spinner.hide();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我的应用程序正在使用具有不同组件和服务的 httpclient 发出请求,并且这些请求发生了两次。我尝试删除订阅,因此它只执行 do 功能,但我的微调器永远不会停止。
有没有人对我应该做什么有任何建议?我想我没有正确使用 rxjs 但不确定修复是什么。
你打了next.handle()两次电话。只需返回第一个,无需调用subscribe:
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
this.count++;
if (this.count === 1) {
this.spinner.show();
}
return next.handle(req)
.catch((err: any) => {
this.count--;
return Observable.throw(err);
}).do(event => {
if (event instanceof HttpResponse) {
this.count--;
if (this.count === 0) setTimeout(this.spinner.hide());
}
});
}
Run Code Online (Sandbox Code Playgroud)
小点建议,升级到angular6以利用新的rxjs和treeshaking
| 归档时间: |
|
| 查看次数: |
1682 次 |
| 最近记录: |