类型“ Observable <object>”上不存在“ catch”

时间:2018-12-10 16:48:18

标签: angular compilation try-catch

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { AppError } from './../common/app-error';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  private url = 'http://jsonplaceholder.typicode.com/posts';

  constructor(private http:HttpClient) { }
    
    getPosts(){
    return this.http.get(this.url);
    }
    createPost(post){
    return this.http.post(this.url, JSON.stringify(post));
    }
    updatePost(post){
    return this.http.put(this.url + '/' + post.id, JSON.stringify(post));
    }
    deletePost(id){
    return this.http.delete(this.url + '/' + id)
      .catch((error:Response)=>{
       return Observable.throw(new AppError(error));
        
      });
    }
  }

此处.catch部分的编译时间错误。 我只想执行错误处理。并通过导入使用catch,但是它将显示错误。类型中不存在“捕获” “可观察”

1 个答案:

答案 0 :(得分:2)

使用rxjs error handling - catch的错误处理功能。您的代码将如下所示:

deletePost(id){
return this.http.delete(this.url + '/' + id)
   .pipe(catchError(err => of(new AppError(err))))
}