The error message stating that property 'catch' does not exist on type 'Observable<IEmployee[]>' cannot be fixed by simply adding the import 'rxjs/add/operator/catch'

When I hover over .catch(this.errorHandler), an error message is displayed

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

I am unable to import the catch function into Angular Typescript.

Upon hovering over .catch(this.errorHandler), the following error message appears:

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

As suggested in another Stack Overflow post: Property 'catch' does not exist on type 'Observable<any>' I should simply add:

import 'rxjs/add/operator/catch'

I have also attempted importing

import {Observable} from 'rxjs/Rx';

and

import { catchError } from 'rxjs/operators'; 

and using catchError instead of catch.

However, none of these methods proved successful

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

Answer №1

There are a couple of things to note:

  1. Instead of using catch, opt for catchError

  2. Make sure to use it in conjunction with .pipe()

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

Answer №2

Here is a recommended way to handle errors using 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) {

     //Using throwError instead of Observable.throw
      return throwError(error.error.message ||"Server Error");
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

What is the meaning of "bootstrapping" as it relates to Angular 2?

I found a question that is similar to mine, but I think my case (with version 2) has enough differences to warrant a new discussion. I'm curious about the specific purpose of calling bootstrap() in an Angular 2 application. Can someone explain it to ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

Angular 8 HTTP Interceptor causing issues with subscriptions

I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

What prevents the creation of an Angular app without any content?

Why am I unable to create an empty Angular app? I have been following the guidelines provided on the official documentation: https://angular.io/guide/setup-local. To start off, I installed Angular using the command: npm install -g @angular/cli. Now, whe ...

Tips for asynchronously loading moment.js timezone data in Angular

I have recently added the following package: npm install moment-timezone --save Within my angular component, I am utilizing it in this manner: import * as moment from 'moment-timezone'; moment().tz('America/New York'); However, I su ...

The WebElement can be identified using cssSelector or xpath in the web browser. It may not be null, but it is also not present, clickable, or enabled

Is this a Selenium issue or an Angular issue? I'm not sure..I have a button element with the following HTML code. This is on an angular website, by the way. <div class="col-xs-12 col-sm-3 col-sm-push-6 col-lg-3" css="1"> <button class="btn b ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Issue encountered in node_modules/@ngrx/store/src/models.d.ts(58,58): TypeScript error TS2304 - Unable to locate identifier 'unknown'

I am currently exploring the implementation of the REDUX Pattern in my upcoming Angular project, but I am facing issues with importing the necessary libraries. ERROR in node_modules/@ngrx/store/src/models.d.ts(58,58): error TS2304: Cannot find name &apo ...

Angular 11 reactive form not reflecting real-time changes in input field

I'm currently working on an Angular project and I need to dynamically update a reactive form field with data retrieved from an API called getNextCode(). I have a function that calls the API service like this: ngOnInit(): void { this.NextCodeService.g ...

Controlling the upper and lower limits in an input field for numerical values while manually typing in the text

Trying to implement an Angular component input with number type that allows setting a maximum and minimum value. Here is the code snippet used for calling the component in HTML: <app-input-number [(value)]="inputMinMaxValueNumber" [min]="min" [max]="m ...

How to dynamically set a background image using Ionic's ngStyle

I've been trying to set a background image on my card using ngStyle Take a look at my code below: <ion-slides slidesPerView="1" centeredSlides (ionSlideWillChange)= "slideChange($event)" [ngStyle]= "{'background-image': 'ur ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Typescript: Deciphering how to interpret a string with a mix of characters and numbers

Is there a way in TypeScript to add 40 to a variable of type string | number, and return a result as a string | number? My initial approach was to parse the variable to a number, then perform the addition, but how can I ensure that the variable is proper ...

Karma Jasmin is puzzled as to why her tests are failing intermittently, despite the absence of any actual test cases

In this snippet, you will find my oninit method which I am instructed not to modify. ngOnInit(): void { this.setCustomizedValues(); this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => { ...

Error: The "start" script is missing in your Angular project

Recently, I created an Angular project in VS Code. Everything seemed to be going smoothly until I attempted to run npm start, only to encounter the following error: npm ERR! Missing script: "start" in angular project" After inspecting my package.json fi ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...