Handling Errors in RXJS Angular - Utilizing .subscribe and Observable Strategy

For creating a new product using a backend API, the Angular frontend code needs to make a call to the API. I am interested in learning how to implement error handling with the use of .subscribe method. Currently, I am utilizing HTTPClient along with Observable and exploring the error handling capabilities provided by RXJS.

The application is expected to interact with the API as an Observable and subscribe to it.

The API at /create endpoint should handle both success and failure scenarios: - If the API returns 200, a success message should be displayed. - If the API returns 400, it should trigger an error.

Pseudo Code:


import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

ID = 'foo';
this.http.post('/api/create', {
    productName: this.form.value.productName,
    productValue: this.form.value.productValue,
}).subscribe(
    resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
);

private onSubmitSuccess(resp) {
    console.log(resp);
    this.ID = resp.ID;
    this.submitSuccess = true;
    this.submitFailed = false;
}

private onSubmitFailure(resp) {
    console.log(resp);
    this.submitFailed = true;
    this.submitSuccess = false;
}  

Answer №1

In the past, the format used to look like this:

this.http.get(url).subscribe(
 data =>
 {
   //perform an action
 },
 error =>
 {
   //handle any errors
 }
);

However, in the most recent updates, this style has been marked as deprecated. Now, you must use:

this.http.get(url).subscribe(
 {
   next: (data) => 
   {
     //perform an action
   },
   error: (error) =>
   {
     //handle any errors
   }
 }
);

Answer №2

Dealing with request errors. This resource is directly from the official Angular documentation

fetchConfig() {
  return this.http.get<Configuration>(this.configEndpoint)
    .pipe(
      catchError(this.handleErrors)
    );
}

private handleErrors(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // Handle client-side or network error appropriately.
    console.error('There was an error:', error.error.message);
  } else {
    // The backend delivered a failed response code.
    // Check the response body for possible causes of failure,
    console.error(
      `Backend responded with code ${error.status}, ` +
      `response body: ${error.error}`);
  }
  // Return an observable with a user-friendly error message
  return throwError(
    'Something went wrong; please try again later.');
};

Answer №3

If you find yourself unable to utilize the async pipe and are required to use subscribe, employing pipe operators is considered a best practice as it facilitates unsubscribing when the component is destroyed. It is advised to leverage the operators for implementing logic, reserving subscribe solely for indicating that the stream is being observed. A structured implementation might resemble the following:

  ID = 'foo';
  onDestroy = new Subject<boolean>();

  this.http.post('/api/create', {
      productName: this.form.value.productName,
      productValue: this.form.value.productValue,
  }).pipe(
    catchError(err => {
      onSubmitFailure(err);
      return of(err);
    }),
    takeUntil(this.onDestroy),
    tap(resp => onSubitSuccess(resp)),
  ).subscribe();

  onSubmitSuccess(resp) {
      console.log(resp);
      this.ID = resp.ID;
      this.submitSuccess = true;
      this.submitFailed = false;
  }

  onSubmitFailure(resp) {
      console.log(resp);
      this.submitFailed = true;
      this.submitSuccess = false;
  } 

  ngOnDestroy() {
      this.onDestroy$.next(true);
      this.onDestroy$.unsubscribe();
  }

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

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

When running a callback function, the "this" of an Angular 2 component becomes undefined

One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data. The problem arises when attempting to use the callback function to append t ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Angular Error Handler - Extracting component context information from errors

In the event of a TypeScript error, I am looking to send all of the component's attribute values to a REST API. It would greatly benefit me if I could access the component's context (this) in order to retrieve the values of all attributes within ...

Using AngularJS to retrieve a string array from data stored in Angular Firestore by invoking a function

As a newcomer to Angular, I am attempting to retrieve details from Firebase as a string array using the function below: Firestore : companies > details > app > name: "WM,TT,MP" getCompanies(): string [] { var appl: string [] = [] ; this.db.dat ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

You cannot assign type void to type any

I'm currently working on a component that involves some code: export class AddNewCardComponent { public concept = []; constructor( private _router: Router, private _empDiscService: empDiscService) { } ngOnIni ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. https://i.sstatic.net/ko8Y0.png App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App ...

What is the best way to bring in styles for a custom UI library in Angular 2?

In the realm of UI libraries, I find myself facing a dilemma. Upon importing SCSS styles into my components (such as a button), I noticed that if I instantiate the component button twice in the client app (which has my UI library as a dependency), the SCSS ...

Running into issues with TypeScript in conjunction with Redux-Form and React-Redux connect

My excitement for TypeScript grew until I encountered some frustrating incompatibilities between Redux-Form and React-Redux. I am aiming to wrap a component decorated with reduxForm using the connect decorator from react-redux—this method has always bee ...

Steps for utilizing a function from the parent component to initialize TinyMCE

I have implemented an uploading function in my parent component. As I set up tinymce, I connected the [init] property of my component to the loadConfig() function. <editor [(ngModel)]="data" [init]="loadConfig()"></editor> The loadConfig func ...

Using the length of an array as an iterator within a nested ngFor loop in Angular 9

I am looping through an array of objects where each object contains another array of objects with attributes like "name" and "id". The length of this array of objects (noticias) varies. I am struggling to display these values and have only managed to acce ...

Using *ngFor to dynamically update the DOM when an array is modified via ngrx

Currently, I am utilizing *ngFor to present values from an array: [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' } ] In the html: <div *ngFor="let item of (items$ | async); trackBy: trackById;&quo ...

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...

Efficient Typescript ambient modules using shorthand notation

Exploring the code snippet from the official module guide, we see: import x, {y} from "hot-new-module"; x(y); This syntax raises a question: why is 'x' not within curly brackets? What does this coding structure signify? ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Leverage rxjs/Typescript to transform an array nested within the data received from an external API

Exploring Typescript/Javascript is a new adventure for me, especially as I delve into the world of rxjs. Here's a snippet of code that I've been working with: return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCant ...

Challenges Faced with Implementing Active Reports in Angular 9

After following all the necessary steps outlined in this website to integrate Active Reports with Angular 9 (), I encountered an error when trying to compile my app: ERROR in The target entry-point "@grapecity/activereports-angular" has missing dependen ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...