To prevent duplicate HTTP requests in Angular with RxJS, you can utilize operators such as shareReplay() or manage subscriptions properly. Here’s a concise solution:
Approach with shareReplay
When you make an HTTP request, ensure the observable is shared and replayed so that multiple subscriptions don't trigger additional requests. For instance:
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class DataService {
private data$: Observable<any>;
constructor(private http: HttpClient) {}
getData(): Observable<any> {
if (!this.data$) {
this.data$ = this.http.get('https://api.example.com/data').pipe(
shareReplay(1) // Share and replay the last emitted value
);
}
return this.data$;
}
}
This ensures that even with multiple subscriptions, only one HTTP request is made.