在Observable <Response>中找不到catchError

Pis*_*usa 1 http angular6 rxjs6

我试图从HTTP请求中捕获错误,并基于错误代码向用户显示错误消息。为此,我使用rxjs中的catchError运算符。

但是我收到这个错误,指出类型Observable <Response>上不存在属性'catchError'

以下是我的package.json

"dependencies": {
"@angular/animations": "^6.0.3",
"@angular/common": "^6.0.3",
"@angular/compiler": "^6.0.3",
"@angular/core": "^6.0.3",
"@angular/forms": "^6.0.3",
"@angular/http": "^6.0.3",
"@angular/platform-browser": "^6.0.3",
"@angular/platform-browser-dynamic": "^6.0.3",
"@angular/router": "^6.0.3",
"bootstrap": "^3.3.7",
"core-js": "^2.5.4",
"rxjs": "^6.0.0",
"zone.js": "^0.8.26"
Run Code Online (Sandbox Code Playgroud)

以下是我正在实现的用于处理http请求的服务中使用的导入。

import { catchError } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Http } from '../../../node_modules/@angular/http';
import { Observable } from 'rxjs';
import { AppError } from './../common/app-error';
import { NotFoundError } from '../common/not-found-error';
Run Code Online (Sandbox Code Playgroud)

这是我从服务器上删除帖子并为预期和意外错误返回自定义错误的功能。

deletePost(id:number){
return this.http.delete(this._url+"/"+id).catchError(
  (error:Response)=>{
    if(error.status===404){
      return Observable.throw(new NotFoundError());
    }
    return Observable.throw(new AppError(error));
  }
);
Run Code Online (Sandbox Code Playgroud)

}

但是,当我尝试删除帖子时,出现以下错误。

this.http.delete(...).catchError is not a function
Run Code Online (Sandbox Code Playgroud)

根据我的理解,我还为rxjs引用了以下API, catchError函数期望将Observable作为输入。如果有人可以帮助我解决此问题,我将不胜感激。谢谢。

Pis*_*usa 5

我想到了。从rxjs 6开始,必须先使用pipe()运算符,然后才能使用catchError之类的运算符。因此,应按如下所示修改代码。

deletePost(id:number){
return this.http.delete(this._url+"/"+id)
.pipe(
  catchError(
    (error:Response)=>{
      if(error.status===404){
        return Observable.throw(new NotFoundError());
      }
      return Observable.throw(new AppError(error));
    }
));}
Run Code Online (Sandbox Code Playgroud)

更新

为使此功能正常工作,需要进行一些更改,因为rxjs6的throw函数实现也已更改。现在,必须使用throwError()函数来代替可观察到的throw错误函数。上述任务的实现如下。

  deletePost(id:number){
return this.http.delete(this._url+"/"+id)
.pipe(
  catchError(
    (error:Response)=>{
      if(error.status===404){
        console.log(error);
        return throwError(new NotFoundError(error));
      }
      return throwError(new AppError());
    }
));}
Run Code Online (Sandbox Code Playgroud)

我希望有人会对此有所帮助,并节省几个小时的时间。干杯!