1

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")
      }
    }
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
  • 2
    Don't, ever again, use imports of the form `import 'rxjs/add/...`. Those were for an obsolete version of RxJS. Use pipable operators, the one you need to use being called catchError (and being already imported). https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md – JB Nizet Jun 20 '19 at 16:50

2 Answers2

2

Two issues:

  1. Use catchError not catch

  2. Use it with .pipe()

     return this.http.get<IEmployee[]>(this._url)
                .pipe(catchError(this.errorHandler));
    
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
0

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");
  };
}
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23