Suraj Nerati
Suraj Nerati

Reputation: 99

Incorrect value - Looping Servicecalls in Angular

I'm trying to get value of this.totalbuilds_overview_jaas which will update after every service call. Below is the code

constructor(private dataservice: CicdDashboardApiService) {   }

  calculating_jaas_builds_count(){
     var counter:number = 0;
    console.log("calculating jaas total builds..")
    this.jaasclients.forEach(element => {
      this.dataservice.getTotalBuildCounts_jaas(element.url,element.token).subscribe((response: TotalBuilds[]) => {
      counter = this.total_getObject_jaas(response['jobs'])
      this.totalbuilds_overview_jaas += counter
     },err => console.log(err))
    })
  }

The problem is - this.totalbuilds_overview_jaas not giving constant value. It keeps varying when I reload the application. How can I make necessary changes to load this.totalbuilds_overview_jaas only after completing the loop.

*this.total_getObject_jaas(response['jobs']) => returns some number

Upvotes: 0

Views: 25

Answers (1)

Dmitriy T
Dmitriy T

Reputation: 201

The problem is likely that you don't really know when the calls to CicdDashboardApiService will actually be complete at the time of retrieving this.totalbuilds_overview_jaas because calculating_jaas_builds_count() is actually asynchronous.

You need to wait for all the service requests to complete before you can get the total count. One way of doing it is simply with promises:

  async calculating_jaas_builds_count() {
    console.log("calculating jaas total builds..");

    // Execute a data service request for each of the clients
    const promises = this.jaasclients.map(element =>
      this.dataservice
        .getTotalBuildCounts_jaas(element.url, element.token)
        .pipe(take(1))
        .toPromise()
    );

    // Wait for all requests to complete
    const responses = await Promise.all(promises);

    // Process each of the service responses and collect the jobs
    for (const response of responses) {
      this.totalbuilds_overview_jaas += response["jobs"];
    }
  }

You can then await this method and only then you can get the total count:

await calculating_jaas_builds_count();
console.log('total count', this.totalbuilds_overview_jaas)

I'm not 100% sure about the structure of your service response because your typings say the response is an array of TotalBuilds, but on the next line you say response['jobs'], which seems like a mistake in itself. In any case, hope you get the idea.

Upvotes: 1

Related Questions