Home >Web Front-end >JS Tutorial >Global Error Handling in Angular

Global Error Handling in Angular

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 01:24:10995browse

Global Error Handling in Angular

To catch errors while subscribing to a service in Angular 17 and toggle the loading or other UI states, you can use the subscribe method of observables along with RxJS operators like catchError. Here’s a step-by-step approach:

Example:

1. Service call with a loading indicator:

  • Set a loading flag to true before starting the service call.
  • Subscribe to the service and handle success and error responses.
  • Reset the loading flag to false when the call completes (either on success or failure).

2. Handling errors:

  • Use the catchError operator inside the observable pipeline to catch and handle errors.
  • Optionally display a notification or error message using something like Toastr.

Sample Code:

import { Component } from '@angular/core';
import { MyService } from './my-service.service'; // Your service here
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ToastrService } from 'ngx-toastr'; // If you are using Toastr for notifications

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html'
})
export class MyComponent {
  loading = false;   // Flag to toggle loading indicator
  data: any = null;  // Variable to hold the service response data

  constructor(private myService: MyService, private toastr: ToastrService) { }

  getData() {
    this.loading = true;  // Start loading before the service call
    this.myService.getData()  // Call the service method
      .pipe(
        catchError((error) => {
          this.toastr.error('Failed to fetch data', 'Error');  // Show an error notification
          console.error(error);  // Log the error (optional)
          this.loading = false;  // Stop loading on error
          return of(null);  // Return an empty observable to prevent further issues
        })
      )
      .subscribe(
        (response) => {
          this.data = response;  // Handle successful response
          this.toastr.success('Data fetched successfully!', 'Success');  // Success notification
        },
        () => {
          this.loading = false;  // Stop loading on error (handled in catchError as well)
        },
        () => {
          this.loading = false;  // Stop loading on completion (either success or error)
        }
      );
  }
}

Key Points:

  • Loading Flag: The loading flag is used to show/hide the loading spinner. It is set to true before the service call and reset to false in both the error and completion callbacks.

  • Error Handling: The catchError operator is used to catch the error, handle it (e.g., log it, show a notification), and prevent the application from crashing. It returns an empty observable (of(null)) so that the subscription can complete.

  • Toastr Notification: The ToastrService is used to display notifications for success and error events. Adjust this based on your notification system if you're using something else.

This approach helps you maintain the loading state, catch errors, and gracefully handle both success and failure scenarios while keeping the UI responsive.

The above is the detailed content of Global Error Handling in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn