Combine multiple requests for request and push api only once in Angular 2

One service is called simultaneously by several components. How can we avoid firing multiple api calls and wait for the api to finish and return to the 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 simultaneously by multiple components. How can I avoid multiple api calls.

+3


source to share


1 answer


Here's how you can do it:



@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));
}

      

+2


source







All Articles