Angular 拦截器正在加倍请求
我有两个拦截器HttpErrorInterceptor和AuthInterceptor。它们的顺序如下:Angular 拦截器正在加倍请求,angular,Angular,我有两个拦截器HttpErrorInterceptor和AuthInterceptor。它们的顺序如下: export const httpInterceptorProviders = [ { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ];
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];
问题:当我订阅这个.userService.register()
时,它总是返回“正在使用的电子邮件”,即使注册成功并且我可以在数据库中看到新用户。这让我觉得请求被执行了两次。对于其他HTTP请求可能也是如此
当前结果:电子邮件已在使用中。(双重要求?)
预期结果:
成功注册
从提供程序中删除HttpErrorInterceptor时的结果:
这是预期的结果,但“错误”
您的拦截器有
重试(1)
,这就是他们发出重复请求的原因。这确实是问题所在。非常感谢。
ERROR
{…}
error: Object { error: SyntaxError, text: "Successfully registered." }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, lazyInit: lazyInit() }
message: "Http failure during parsing for http://localhost:5000/api/users"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:5000/api/users"
<prototype>: Object { … }
core.js:6014:19
ERROR
{…}
error: "E-mail already in use."
headers: Object { normalizedNames: Map(0), lazyUpdate: null, lazyInit: lazyInit() }
message: "Http failure response for http://localhost:5000/api/users: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "http://localhost:5000/api/users"
<prototype>: Object { … }
core.js:6014:19
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { HttpErrorHandlerService } from './http-error-handler.service';
@Injectable({ providedIn: 'root' })
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private errorHandler: HttpErrorHandlerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
return next.handle(request)
.pipe(
// retry once before checking the error status
retry(1),
catchError((error: HttpErrorResponse) => {
this.errorHandler.handle(error);
return throwError(error);
})
);
}
}