【问题标题】:rxjs catchError import issue for rxjs@6.3.3rxjs@6.3.3 的 rxjs catchError 导入问题
【发布时间】:2019-10-01 11:13:17
【问题描述】:

尝试为 rxjs v6.3.3 导入 catchError 但导入看起来不起作用。使用 catch 时出现错误。

发现了类似的问题,但似乎没有帮助我。

代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IWinServices } from './WinServices';
import { Observable } from 'rxjs';
import { catch } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WinServicesService {

  private _url : string = './assets/Data/WinServicess.json'
  constructor(private http: HttpClient) { }

  getWinServices() :Observable <IWinServices[]>  {
      return this.http.get<IWinServices[]>(this._url).catch (this.errorHandler);

  }

  errorHandler(error: HttpErrorResponse) {

    return Observable.throw(error.message || "Server Error");
  }
}

尝试了可能的解决方案:没有一个对我有用

import { catchError } from 'rxjs/operators';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Rx';

错误:

Property 'catch' does not exist on type Observable&lt;IWinServices[]&gt;'.ts(2339)

ERROR in src/app/employee.service.ts(16,52): error TS2339: Property 'catch' does not exist on type 'Observable<IEmployee[]>'

【问题讨论】:

  • catchError 将用作可管道操作符。我没有看到你在代码中的任何地方使用它。
  • 您收到的错误是因为您在 Observable 上使用了 .catch,这是不可能的
  • 看来我用的是旧教程,我会用管道切换新版本

标签: angular typescript visual-studio-code rxjs rxjs6


【解决方案1】:

错误解释了问题。

error TS2339: Property 'catch' does not exist on type 'Observable&lt;IEmployee[]&gt;'

在 rxjs v6+ 中,您不再将运算符链接到可观察调用。

相反,试试这个...

像下面这样导入import { catchError } from 'rxjs/operators';

像这样管道catchError


return this.http.get<IWinServices[]>(this._url).pipe(
    catchError(() => {
       // error handling logic here
    })
)

查看这个很棒的网站以供参考。 https://www.learnrxjs.io/operators/error_handling/catch.html

最后说明: 不要使用这个import 'rxjs/add/operator/catch';,不推荐使用它,因为它不是作用域导入。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2019-06-23
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多