如何在angular2 cli项目中由多个组件并行调用单个ajax请求 [英] How to call single ajax request by multiple components parallely in angular2 cli project

查看:110
本文介绍了如何在angular2 cli项目中由多个组件并行调用单个ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景是,有一个具有方法getWebservicedata()的服务(json-data-service.ts),该方法返回http.post(url),即在调用方法时进行ajax调用. 我有不同的组件(例如pie-chart-components,bar-chart-component,line-chart组件等),它们都在同一页面上同时创建.它们都有各自不同的元数据(clientJson)和一个可观察的对象.

The scenario is , there is a single service(json-data-service.ts) having a method getWebservicedata() which returns http.post(url) ie it makes an ajax call when method is called. I have different components like(pie-chart-components,bar-chart-component, line-chart components etc) and they all created at the same time on a single page. They all have their different metadata(clientJson) and a single observable.

有没有办法,我们可以通过多个组件并行地发出单个ajax请求.

Is there any way, by which we can make a single ajax request by multiple components parallely.

换句话说,是否有任何方式使得在执行ajax请求之前,它会从不同组件(PieComponent.ts,LineComponent.ts等)中获取所有元数据,并从同一URL中获取不同元数据的数据(clientJson)不同的组件,同时并行?

In other words, is there any way such that before ajax request is executed, it takes all the metadata from different components(PieComponent.ts,LineComponent.ts etc) and fetch data from the same url for different metadata(clientJson) of different components, at the same time parallely?

    getSolrData(clientJson): Observable<JsonData[]> {
    console.log('Retriving Data from Solr Server.......' + JSON.stringify(clientJson));
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = "http://183.82./PI3_Sor_WebSer/solrSe"; 
    return this.http.post(url, clientJson).map((res: Response) => res.json());
  }

pie-chart.component.ts

initData() {

    let clientJson = {
      "aoId": "M_AO_918","viewBys": ["usstate"]----------------- };

    this.jsonDataService.getSolrData(clientJson).subscribe(
      success => this.buildPieChart(success),
      error => this.errorMessage = error
    );
  }
  buildPieChart(jsonData) {
-----------
}

line-chart.component.ts

initData() {

    let clientJson = {
      "aoId": "M_AO_918","viewBys": ["brands"]----------------- };

    this.jsonDataService.getSolrData(clientJson).subscribe(
      success => this.buildlineChart(success),
      error => this.errorMessage = error
    );
  }
  buildlineChart(jsonData) {
-----------
}

推荐答案

您需要使用rxjs .share()方法(

You want something using the rxjs .share() method (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/share.md). Basically it allows multiple subscribers to share the same observable sequence.

export class Service {
  observableShare: Observable<string>; // store the shared observable
  
  constructor(private http: Http){}
  
  getData(){
    if(this.observableShare){ // if api is still processing, return shared observable
        return this.observableShare;
    }else{ // else api has not started, start api and return shared observable
      this.observableShare = this.http.post('url')
        .map(res => res.json())
        .share(); // share observable sequence among multiple subscribers
      
      return this.observableShare;
    }
    
  }
}

这是工作正常的朋克( https://plnkr.co/edit/MU4aoFI34ZGjjtQ5wS9j?p = preview ),您可以在控制台中看到,有3个单独的订阅共享相同的可观察序列(http请求).

Here is a working plunkr (https://plnkr.co/edit/MU4aoFI34ZGjjtQ5wS9j?p=preview) you can see in the console, 3 separate subscribes are sharing the same observable sequence (http request).

这是另一个例子,将结果进一步存储到服务中( https://plnkr.co/edit/M9ZIViYhSbKzPlzKXC7H?p=preview ).它充当缓存,因此,如果稍后加载的组件需要数据,则不需要额外的api调用.但是您不需要此功能.

Here is another example goes one step further and stores the result in the service (https://plnkr.co/edit/M9ZIViYhSbKzPlzKXC7H?p=preview). This acts as a cache, so if a component that is loaded later needs the data, an additional api call is not needed. But you do not need that functionality for this piece.

这篇关于如何在angular2 cli项目中由多个组件并行调用单个ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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