user1853803
user1853803

Reputation: 659

Combine multiple request for a request and hit api only once in Angular 2

One service is being called in multiple components at the same time. How can we avoid firing multiple api calls and wait till the api has finished and returns observable.

@Injectable()
export class SomeService {
    private data: string;
    private _subject$: AsyncSubject<string[]> = new AsyncSubject<stirng[]>();
    private obs: Observable<any>;
    constructor() { }

 public currentData$(): Observable<string[]> {
   this.getData();
   return this._subject$.asObservable();
}

private getData() {
  this.http.get(this.url)
  .map((r) => r))
  .share()
  .subscribe((res) => {
    this._subject$.next(res);
    this._subject$.complete();
  });
}

Here currentData$() is being called by multiple components at the same time. How can I avoid multiple api calls.

Upvotes: 3

Views: 558

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105439

Here is how you can do that:

@Injectable()
export class SomeService {
    private data: string;
    private _subject$: AsyncSubject<string[]>;
    private obs: Observable<any>;
    constructor() { }

 public currentData$(): Observable<string[]> {
   if(!this._subject$) {
      this._subject$ = new AsyncSubject<stirng[]>();
      this.getData().subscribe(this._subject$);
   }

   return this._subject$;    
}

private getData() {
  return this.http.get(this.url).map((r) => r));
}

Upvotes: 2

Related Questions