组合多个请求请求并在Angular 2中只打一次api

时间:2017-07-12 16:25:19

标签: angular

同时在多个组件中调用一个服务。我们怎样才能避免触发多个api调用并等到api完成并返回可观察的。

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

这里currentData $()同时被多个组件调用。如何避免多个api调用。

1 个答案:

答案 0 :(得分:2)

以下是如何做到这一点:

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