在Angular 2中组合多个请求并仅点击一次api [英] Combine multiple request for a request and hit api only once in Angular 2

查看:20
本文介绍了在Angular 2中组合多个请求并仅点击一次api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时在多个组件中调用一个服务.我们如何避免触发多个 api 调用并等待 api 完成并返回 observable.

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

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

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

推荐答案

您可以这样做:

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

这篇关于在Angular 2中组合多个请求并仅点击一次api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆