我有两个拦截器HttpErrorInterceptor和AuthInterceptor。它们具有以下顺序:
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];
问题::当我订阅this.userService.register()
时,即使注册成功,它也会始终返回“正在使用电子邮件”,并且我可以在数据库中看到新用户。这使我认为该请求被执行了两次。对于其他HTTP请求来说可能是相同的。
当前结果:电子邮件已在使用中。 (双重要求?)
预期结果: 成功注册。
从提供程序中删除HttpErrorInterceptor的结果:
那是预期的,但是是“错误”?
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
我从提供程序中删除AuthInterceptor的结果:
问题仍然存在。
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
首先,它不是来自后端,因为我已使用NSwag和Postman对其进行了测试。在那里工作正常。这两个提供程序都添加到app.module.ts
中,而不是添加到延迟加载的模块中,因为stackoverflow上存在类似的问题。
我的自我解释是,两个拦截器都一次处理同一请求,甚至以某种方式this.userService.register()
都只被调用一次(由console.log确认)。
我不知道该如何解决,但它来自HttpErrorInterceptor。我当时在考虑使用HttpBackend
,但实际上我需要HttpErrorInterceptor的那些模式来验证错误。
有什么想法吗?
https://stackblitz.com/edit/angular-dziwbx
http-error.interceptor.ts
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);
})
);
}
}
答案 0 :(得分:1)
您的拦截器有retry(1)
,这就是为什么他们要重复请求。