这是我在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'。
错误在第26行,即:
.catchError(this.handleErrorObservable);
我尝试过很多东西,但没有任何效果......任何人都可以解决这个问题吗?
用'catch'做了但是没有用,所以我去了'catchError'但是仍然有这个错误......
答案 0 :(得分:6)
catchError
需要导入,然后在.pipe
中使用:
import {catchError} from 'rxjs/operators/catchError';
return this.http.get(this.url)
.pipe(
map(this.extractData),
catchError(this.handleErrorObservable)
);
答案 1 :(得分:3)
您需要在pipe
内使用它,如下所示:
getBooksWithObservable(): Observable<Book[]> {
return this.http.get(this.url)
.pipe(map(this.extractData),catchError(this.handleErrorObservable));
}
答案 2 :(得分:1)
catchError
必须位于pipe
。
import { Observable, pipe } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
getBooksWithObservable(): Observable<Book[]>
{
return this.http.get(this.url)
.pipe(
map(this.extractData),
catchError(this.handleErrorObservable)
);
}
答案 3 :(得分:-1)
您必须更改为:
...
return this.http.get(this.url).subscribe((r:Author)=>console.log("GOOD"),err=>console.log("ERROR))
...
这是rxjs的问题