简体   繁体   中英

Property 'catch' does not exist on type 'Observable<IEmployee[]>'.ts(2339) Error is not resolved by adding import 'rxjs/add/operator/catch';

When I hover over .catch(this.errorHandler) , I get a the error message

Property 'catch' does not exist on type 'Observable'.ts(2339)

I can not import the catch function into angular typescript.

When I hover over .catch(this.errorHandler) , I get a the error message

Property 'catch' does not exist on type 'Observable'.ts(2339)

According to another stack post: Property 'catch' does not exist on type 'Observable<any>' I should just add:

import 'rxjs/add/operator/catch'

I also tried importing

import {Observable} from 'rxjs/Rx';

and

import { catchError } from 'rxjs/operators'; 

and using catchError instead of catch.

None of these worked

    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")
      }
    }

Two issues:

  1. Use catchError not catch

  2. Use it with .pipe()

      return this.http.get<IEmployee[]>(this._url) .pipe(catchError(this.errorHandler)); 

Try this (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");
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM