[英]Angular 5 intercept - requests are duplicated
我在 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();
}
});
}
}
如您所見,我的應用程序正在使用具有不同組件和服務的 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());
}
});
}
小建議,升級到angular6,利用新的rxjs和treeshaking
請在此處查看有關微調器和計數請求的解決方案。
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.count++;
if (this.count === 1) {
this.spinner.show();
}
return next.handle(request)
.pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.count--;
if (this.count === 0) setTimeout(this.spinner.hide());
}
}, (err: any) => {
this.count = 0;
setTimeout(this.spinner.hide());
})
);
}
我有同樣的重復請求問題。 原來我使用了角度表單,並且在按鈕上有一個 (click) 事件,在表單元素上有一個 (ngSubmit) 事件。 通過刪除其中一個來解決它,並且消除按鈕的抖動永遠不會受到傷害;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.