当我将鼠标悬停在.catch(this.errorHandler)
上时,我收到错误消息
属性"catch"在类型"可观察"上不存在.ts(2339)
我无法将 catch 函数导入角度打字稿。
当我将鼠标悬停在.catch(this.errorHandler)
上时,我收到错误消息
属性"catch"在类型"可观察"上不存在.ts(2339)
根据另一个堆栈帖子: 属性"catch"在类型"可观察<任何>"上不存在 我应该补充一点:任何>
import 'rxjs/add/operator/catch'
我也尝试导入
import {Observable} from 'rxjs/Rx';
和
import { catchError } from 'rxjs/operators';
并使用捕获错误而不是捕获。
这些都不起作用
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable, fromEventPattern } from 'rxjs';
import 'rxjs/add/operator/catch';
import {catchError} from "rxjs/operators"
import 'rxjs/add/observable/throw';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url : string = "../assets/data/employees.json";
constructor(private http: HttpClient) { }
getEmployees(): Observable<IEmployee[]>{
return this.http.get<IEmployee[]>(this._url)
.catch(this.errorHandler)
}
errorHandler(error:HttpErrorResponse){
return Observable.throw(error.message ||"Server Error")
}
}
两个问题:
-
使用
catchError
不catch
-
将其与 .pipe() 一起使用
return this.http.get<IEmployee[]>(this._url) .pipe(catchError(this.errorHandler));
试试这个(catchError with throwError):
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable, fromEventPattern, throwError} from 'rxjs';
import {catchError} from "rxjs/operators"
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url : string = "../assets/data/employees.json";
constructor(private http: HttpClient) { }
getEmployees(): Observable<IEmployee[]>{
return this.http.get<IEmployee[]>(this._url)
.pipe(catchError(this.handleError));
}
handleError(error: HttpErrorResponse) {
//throwError instead of Observable.throw
return throwError(error.error.message ||"Server Error");
};
}