属性'catch'在类型"Observable<IEmployee[]>'.ts(2339)上不存在 错误无法通过添加导入"rxjs/add/operator/catch"来解决;



当我将鼠标悬停在.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")
}
}

两个问题:

  1. 使用catchErrorcatch

  2. 将其与 .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");
};
}

最新更新