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:
2. Handling errors:
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!