简体   繁体   English

Angular 8 Interceptors - 如何处理状态 200 中的响应

[英]Angular 8 Interceptors - How to process response in status 200

Background背景

We are migrating an AngularJS app to newest Angular version.我们正在将 AngularJS 应用程序迁移到最新的 Angular 版本。 We process http requests by ALWAYS receiving status code 200, if there is an error, we still get status code 200 (excluding 404 - 500, and errors regarding the actual server or user connection).我们通过始终接收状态代码 200 来处理 http 请求,如果出现错误,我们仍然会收到状态代码 200(不包括 404 - 500,以及有关实际服务器或用户连接的错误)。 For example, if User Token expires and we make a request, we get a status code 200 with a body of errorCode: number, message: string.例如,如果用户令牌过期并且我们发出请求,我们会得到一个状态代码 200,其主体为 errorCode: number, message: string。 This will not change .这不会改变

Problem问题

Using the same example about the token, all the code examples I've seen regarding Interceptors processing the invalid token issue and refresh it in the CatchError of the observable:使用关于令牌的相同示例,我看到的所有代码示例都涉及拦截器处理无效令牌问题并在 observable 的 CatchError 中刷新它:

return next.handle(request).pipe(
  map((event: HttpEvent<any>) => {
    <Process Response, and errors in my project>
  }),
  catchError((error: HttpErrorResponse) => {
    <Process Invalid Token in code examples>
  }),
);

This Code examples are not working for me because as I said, in my project we process the errors in the response section, not catchError.此代码示例对我不起作用,因为正如我所说,在我的项目中,我们处理响应部分中的错误,而不是 catchError。 When we get an Invalid Token issue, we refresh the token and retry the original call that failed.当我们收到无效令牌问题时,我们刷新令牌并重试失败的原始调用。

It's a lot easier if we process in catchError because it's expecting an observable and will handle the Observable by it's own, but in the response section, it's not expecting an observable... I managed to make the call to refresh the token in the response section and retry the http call that had the error but when I try to return the response that worked, it never reached the scope of the first call.如果我们在 catchError 中处理会容易得多,因为它期待一个可观察的对象,并且会自己处理可观察对象,但在响应部分,它不期待一个可观察对象......我设法在响应中调用刷新令牌部分并重试出现错误的 http 调用,但是当我尝试返回有效的响应时,它从未达到第一次调用的范围。

Any ideas how I can make the refresh call and retry the first http call out of the catchError?任何想法如何进行刷新调用并重试 catchError 中的第一个 http 调用?

All you need to do in this case is parse the body of the response in the interceptor and return在这种情况下你需要做的就是在拦截器中解析响应的主体并返回

if (res.body.includes(...)) {

           throw of(new HttpErrorResponse({status: 500, statusText: 'Simulated erorr'}));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM