Example of exhaustMap
Let’s consider a simple example where we want to make an HTTP request to fetch user data whenever a button is clicked. If the button is clicked again before the previous request completes, we want to ignore the new click.
Step 1: Install HttpClient
Make sure you have the HttpClientModule
imported in your app module:
typescripimport { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [/* your components */],
imports: [
HttpClientModule,
/* other imports */
],
bootstrap: [/* your bootstrap component */]
})
export class AppModule { }
Step 2: Create a Service
Create a service that fetches user data from an API:
typescriimport { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) { }
getUsers(): Observable<any> {
return this.http.get<any>(this.apiUrl);
}
}
Step 3: Create a Component
In your component, use exhaustMap
to handle the button clicks:
typescriptimport { Component } from '@angular/core';
import { Subject } from 'rxjs';
import { exhaustMap } from 'rxjs/operators';
import { UserService } from './user.service';
@Component({
selector: 'app-user',
template: `
<button (click)="loadUsers()">Load Users</button>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserComponent {
users: any[] = [];
private loadUsersSubject = new Subject<void>();
constructor(private userService: UserService) {
this.loadUsersSubject.pipe(
exhaustMap(() => this.userService.getUsers())
).subscribe(data => {
this.users = data;
});
}
loadUsers() {
this.loadUsersSubject.next();
}
}
Explanation
Service (
UserService
): Defines a method to fetch user data from an API.Component (
UserComponent
):- Subject: A
Subject
(loadUsersSubject
) is created to emit events when the button is clicked. - exhaustMap: The
loadUsersSubject
is piped withexhaustMap
, which subscribes to thegetUsers()
observable when an event is emitted. If another event is emitted before the request completes, it ignores it. - Template: A button to load users and a list to display the fetched user data.
- Subject: A
Summary
exhaustMap
is a powerful operator for controlling the flow of observables and managing concurrency in Angular applications. In this example, it ensures that only the first button click's request is processed while subsequent clicks are ignored until the first request completed.
No comments:
Post a Comment