rxjs@6.3.3的rxjs catchError导入问题

时间:2019-05-14 12:12:36

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

尝试为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<IWinServices[]>'.ts(2339)

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

1 个答案:

答案 0 :(得分:1)

错误说明了问题所在。

  

error TS2339: Property 'catch' does not exist on type 'Observable<IEmployee[]>'

在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';,因为它不是作用域导入,因此不建议使用。

希望这会有所帮助。