【问题标题】:catchError operator showing problem in angular interceptorcatchError 运算符在角度拦截器中显示问题
【发布时间】:2021-04-07 21:01:00
【问题描述】:

我正在开发一个拦截器来处理 Angular 10 项目中的 http 错误。代码如下:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class HttpErrorHandlerServiceService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
    .pipe(
      map(resp => { 

       }),
      catchError(err => { 

       })
    );
      
  }
}

在 catchError 运算符中显示以下错误。

'(err: any) => void' 类型的参数不能分配给参数 '(错误:任何,捕获:Observable) => ObservableInput<...>'。 类型“void”不可分配给类型“ObservableInput”。

19       catchError(err => {

【问题讨论】:

    标签: angular angular-http-interceptors


    【解决方案1】:

    RxJS catchError 运算符 必须 返回一个 observable。如果您没有要返回的内容,您可以使用 RxJS throwError 函数转发提供的错误。

    import { throwError } from 'rxjs';
    
    return next.handle(req).pipe(
      map(resp => { }),
      catchError(err => { 
        // handle error
        return throwError(err);      // forward the supplied error
      })
    );
    

    【讨论】:

      【解决方案2】:

      您可以通过返回 Observable 消息来优雅地处理错误,例如:

      import { of } from 'rxjs';
      
      catchError(err => of('Error happened'))
      

      或像这样转发:

      catchError(err => throwError(err))
      

      无论哪种方式,您都必须返回Observable。你有很好的例子here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-27
        • 2017-10-09
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 2016-02-02
        • 2014-10-25
        • 2018-07-25
        相关资源
        最近更新 更多