我正在尝试获取this.totalbuilds_overview_jaas
的值,该值将在每次服务调用后更新。下面是代码
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))
})
}
问题是 - this.totalbuilds_overview_jaas没有给出恒定值。当我重新加载应用程序时,它会不断变化。如何仅在完成循环后才对加载this.totalbuilds_overview_jaas
进行必要的更改。
*this.total_getObject_jaas(响应['作业']( => 返回一些数字
问题可能是您并不真正知道在检索this.totalbuilds_overview_jaas
时对CicdDashboardApiService
的调用何时实际完成,因为calculating_jaas_builds_count()
实际上是异步的。
您需要等待所有服务请求完成,然后才能获取总数。一种方法就是简单地承诺:
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"];
}
}
然后,您可以等待此方法,然后才能获得总数:
await calculating_jaas_builds_count();
console.log('total count', this.totalbuilds_overview_jaas)
我不是 100% 确定您的服务响应的结构,因为您的类型说响应是 TotalBuilds 数组,但在下一行您说response['jobs']
,这本身似乎是一个错误。无论如何,希望你明白这个想法。