这是我在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:类型"可观察"上不存在属性"catchError"。
那么错误在第 26 行,那就是:
.catchError(this.handleErrorObservable);
我尝试了很多东西,但没有任何效果...有人能解决这个问题吗?
做了"捕获">但没有工作,所以然后我去"捕获错误",但仍然有这个错误......
catchError
需要导入然后在.pipe
中使用:
import {catchError} from 'rxjs/operators';
return this.http.get(this.url)
.pipe(
map(this.extractData),
catchError(this.handleErrorObservable)
);
你需要像这样在pipe
里面使用它:
getBooksWithObservable(): Observable<Book[]> {
return this.http.get(this.url)
.pipe(map(this.extractData),catchError(this.handleErrorObservable));
}
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)
);
}
您必须更改为:
...
return this.http.get(this.url).subscribe((r:Author)=>console.log("GOOD"),err=>console.log("ERROR))
...
这是 RXJS 的问题