【问题标题】:Property 'catch' does not exist on type 'Observable<IEmployee[]>' [duplicate]'Observable<IEmployee[]>' 类型上不存在属性'catch' [重复]
【发布时间】:2019-04-06 13:43:26
【问题描述】:

我是角度的新手。目前我正在学习 Angular 6 功能。 当我尝试处理错误时,会出现一些问题,例如,

找不到模块:错误:无法解析“rxjs/add/observable/throw” 'D:\WORKSPACE\Angular5\binding\src\app'

找不到模块:错误:无法解析“rxjs/add/operator/catch” 'D:\WORKSPACE\Angular5\binding\src\app'

src/app/employee.service.ts(20,14) 中的错误:错误 TS2339:属性 'Observable' 类型上不存在'catch'

这是我的employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

//It self injectable defendency.
@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");
  }
}

employee.ts

export interface IEmployee{
    id : number,
    name : String,
    age : number
}

我尝试使用下面的链接解决这个问题。但我无法得到我的问题的答案。

Property 'catch' does not exist on type 'Observable'Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]

请给我一些解决方案。谢谢。

【问题讨论】:

  • 这是因为 pipeable/lettable 操作符现在 Angular 能够使用 tree-shakable 并删除未使用的导入并优化应用程序,一些 rxjs 功能发生了变化,您可以参考这篇文章:stackoverflow.com/questions/50196282/…跨度>
  • 如果您仔细阅读了您链接的第一个问题中的最后一个答案,您应该了解您的问题

标签: javascript angular


【解决方案1】:

在 angular 6 中,我们使用 rxjs 6 ,您的示例适用于旧版本的 angular,您可能需要阅读有关 rxjs 6 的更多信息

试试这个方法

  getEmployees(): Observable<IEmployee[]>{
    return this.http.get<IEmployee[]>(this._url)
               .pipe(catchError(this.handlerError));
   }

catch / catchError , RxJS 6 Changes

【讨论】:

    猜你喜欢
    • 2019-11-03
    • 2016-09-01
    • 2018-11-30
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多