Angular 2+ HTTPRequests get data from multiple Cha

2019-09-02 06:09发布

I have a ngx-chart, where I want to insert some data from 2 or more different Mongodb Tables. So I have to make HTTPRequests to two different routes, because each route queries its own Collection/Tables in mongodb. How can I do this inside one big method to get all the data in one chart? Because the requests are asynchronous, I would have to do the data manipulation for the chart inside the HTTP-Request method... that would be OK if I only query from one route (or one table). But as I have to query from more than 1 table, I would have to wait for one request to finish, do data manipulation and save the data somewhere.. Then I would have to do second request and do all the same again.

How can I do this? The problem is, that as soon as I "quit" one httpRequest method where the data lies, the data seems not to be available anymore...

This is my method for one request as for now:

getProduktReservierung(startTime, endTime, DemoID) { 
    return this.http.get('http://localhost:5555/chart/Product/thisprod' + startTime+'.'+endTime+'.' + DemoID)
    .subscribe((res: Response) => {
      this.chartData = res;
      console.log("Produkt Reservation Data:", this.chartData);
      this.dataArray = this.formatDataReservierungen(this.chartData);    
    },
    (err) => {
      if (err.error instanceof Error) {
        console.log('Client-side error occured.');
      } else {
        console.log('Server-side error occured.');
      }
    });
  }

The data manipulation and retrieving part is inside .subscribe() method... how should I do now if I query for other tables data and want to have both the data at once together?

1条回答
该账号已被封号
2楼-- · 2019-09-02 06:52

You should look into forkjoin.

It's similar to promise.all. Create an array of all http request and pass that array into forkJoin and .subscribe() just like you do in case of single http request.

查看更多
登录 后发表回答