Angular Service Notification: Performing Actions after Completion of Multiple API Calls

Introduction:

Performing actions after the completion of multiple API calls is a common requirement in Angular applications. Managing the timing and synchronization of API calls is crucial to ensure the proper flow of data and user experience. In this article, we will explore how to leverage Angular services and HTTP interceptors to track the completion of API calls and execute specific actions when all requests are finished. By implementing this approach, you can enhance the performance and reliability of your Angular application.

To achieve your desired functionality of performing some action in a subcomponent after all API calls are completed, you can use a combination of a service, an HTTP interceptor, and a Subject. Here’s an example implementation:

Create a service to track API calls and notify subscribers:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiTrackerService {
  private apiCallsCount = 0;
  private apiCallsCompleted$ = new Subject<void>();

  incrementApiCallsCount(): void {
    this.apiCallsCount++;
  }

  decrementApiCallsCount(): void {
    this.apiCallsCount--;
    if (this.apiCallsCount === 0) {
      this.apiCallsCompleted$.next();
    }
  }

  getApiCallsCompleted(): Subject<void> {
    return this.apiCallsCompleted$;
  }
}

Create an HTTP interceptor to track API calls using the service:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ApiTrackerService } from './api-tracker.service';

@Injectable()
export class ApiTrackingInterceptor implements HttpInterceptor {
  constructor(private apiTrackerService: ApiTrackerService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
    this.apiTrackerService.incrementApiCallsCount();

    return next.handle(req).pipe(
      tap(
        (event) => {
          if (event instanceof HttpResponse) {
            this.apiTrackerService.decrementApiCallsCount();
          }
        },
        () => {
          this.apiTrackerService.decrementApiCallsCount();
        }
      )
    );
  }
}

Provide the interceptor and the service in your module:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ApiTrackingInterceptor } from './api-tracking.interceptor';
import { ApiTrackerService } from './api-tracker.service';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ApiTrackingInterceptor, multi: true },
    ApiTrackerService
  ]
})
export class YourModule {}

In your subcomponent, subscribe to the apiCallsCompleted$ subject and perform your desired action:

import { Component, OnInit } from '@angular/core';
import { ApiTrackerService } from './api-tracker.service';

@Component({
  selector: 'app-your-subcomponent',
  templateUrl: './your-subcomponent.component.html',
  styleUrls: ['./your-subcomponent.component.css']
})
export class YourSubcomponent implements OnInit {
  constructor(private apiTrackerService: ApiTrackerService) {}

  ngOnInit(): void {
    this.apiTrackerService.getApiCallsCompleted().subscribe(() => {
      // Perform your action in the subcomponent after all API calls are completed
      // ...
    });
  }
}

By following these steps, the ApiTrackerService keeps track of the API calls using the incrementApiCallsCount() and decrementApiCallsCount() methods. The ApiTrackingInterceptor intercepts the API calls and increments or decrements the call count accordingly. The subcomponent subscribes to the apiCallsCompleted$ subject and performs the desired action when all API calls are completed.

Remember to provide the ApiTrackerService and the ApiTrackingInterceptor in the appropriate module or component so that they can be injected and used.

Note: Don’t forget to import the necessary modules and services in the respective files.

Conclusion:

In conclusion, by incorporating the technique of tracking and performing actions after the completion of multiple API calls in Angular, you can take control of the timing and flow of your application. Leveraging Angular services and HTTP interceptors allows you to seamlessly monitor the status of ongoing API calls and execute custom logic once all requests have been processed. This approach empowers you to optimize performance, enhance user experience, and ensure the integrity of your data. Implementing this pattern in your Angular applications will bring efficiency and reliability to your API call handling, making it an essential strategy for any robust Angular development project.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights