错误 TS2339:属性“catchError"在类型“Observable<any>"上不存在 [英] error TS2339: Property &#39;catchError&#39; does not exist on type &#39;Observable&lt;any&gt;&#39;

查看:21
本文介绍了错误 TS2339:属性“catchError"在类型“Observable<any>"上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 book.service.ts 中的代码:

Here is my code in book.service.ts :

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { Book } from './book';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';

//import { Component, OnInit } from '@angular/core';
//import {HttpClient} from "@angular/common/http";
//import { Observable } from 'rxjs/Observable'; 
//import 'rxjs/add/operator/map';
//import 'rxjs/add/operators/catch';
//import 'rxjs/operators/toPromise';

@Injectable()
export class BookService 
{
    url = "http://localhost:4200/assets/data/books.json";

    constructor(private http:Http) { }

    getBooksWithObservable(): Observable<Book[]> 
    {
        return this.http.get(this.url)
                .pipe(map(this.extractData))
                .catchError(this.handleErrorObservable);
    }
    getBooksWithPromise(): Promise<Book[]> 
    {
        return this.http.get(this.url).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }
    private extractData(res: Response) 
    {
        let body = res.json();
        return body;
    }
    private handleErrorObservable (error: Response | any) 
    {
        console.error(error.message || error);
        //console.log("Error in Observable");
        return Observable.throw(error.message || error);
    }
    private handleErrorPromise (error: Response | any) 
    {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }   
}

我在这里收到错误:

src/app/book.service.ts(26,18) 中的错误:错误 TS2339:类型Observable"上不存在属性catchError".

ERROR in src/app/book.service.ts(26,18): error TS2339: Property 'catchError' does not exist on type 'Observable'.

错误在第 26 行,即:

Well the Error is in 26th line and that is :

.catchError(this.handleErrorObservable); 

我尝试了很多东西,但没有任何效果......有人能解决这个问题吗?

I've tried a lot of things but nothing worked... Can anybody solve this?

用'catch'做了但没有用,所以我选择'catchError',但仍然有这个错误......

Did with 'catch' but didn't work, so then I go for 'catchError' but still, there is this error...

推荐答案

catchError 需要导入,然后在 .pipe 中使用:

catchError needs to be imported and then used within .pipe:

import {catchError} from 'rxjs/operators'; 

return this.http.get(this.url)
            .pipe(
              map(this.extractData),
              catchError(this.handleErrorObservable)
            );

这篇关于错误 TS2339:属性“catchError"在类型“Observable<any>"上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆