【问题标题】:Handling Error in HTTPClient get method not working处理 HTTPClient get 方法中的错误不起作用
【发布时间】:2022-02-13 15:43:19
【问题描述】:

我试图在我的服务文件中捕获 HTTP 获取消息中的错误。

这是脚本:

import { Injectable } from '@angular/core';
import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfolio-epic.model';
import { HttpClient, HttpErrorResponse, HttpParams} from '@angular/common/http'
import { config, Observable } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

refreshPortfolioEpicsList(id:number):Observable<PortfolioEpicModel[]>{   
  this.baseUrl=this.conf.getSettings("apiUrl");
  return this.http.get<PortfolioEpicModel[]>(this.baseUrl+ "/api/pepics/"+ id.toString())
    .pipe(catchError(this.errorHandler));
}

errorHandler(error:HttpErrorResponse){
  console.info(error.message);
}

catchError 调用显示此错误:

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

我不明白如何处理它。

我正在使用 Angular 11。

【问题讨论】:

标签: angular typescript rxjs angular11


【解决方案1】:

您可以从rxjs 使用throwError

import { throwError } from 'rxjs';

errorHandler(error: HttpErrorResponse) {
  console.info(error.message);

  return throwError(error.message || "server error.");
}

Sample Solution with Success and Error Demo on StackBlitz

【讨论】:

    【解决方案2】:

    您收到该错误是因为您传递给 RxJS catchError 运算符的 errorHandler 函数需要返回 Observable 或重新抛出错误(就像@Yong Shun 在他的回答中显示的那样)

    catchError 运算符可以在这里查看官方文档:https://rxjs.dev/api/operators/catchError

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 1970-01-01
      • 2023-03-29
      • 2019-02-01
      • 2018-10-07
      • 2017-04-07
      • 2018-10-07
      • 1970-01-01
      相关资源
      最近更新 更多