【问题标题】:Incorrect value - Looping Servicecalls in Angular不正确的值 - Angular 中的循环服务调用
【发布时间】:2020-01-07 21:46:00
【问题描述】:

我正在尝试获取 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(response['jobs']) => 返回一些数字

【问题讨论】:

  • 你能分享你的数据服务吗,或者请尝试参考rxjs forkjoin

标签: angular typescript angular-services angular-observable


【解决方案1】:

问题很可能是在检索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'],这本身似乎是一个错误。无论如何,希望你能明白。

【讨论】:

  • 我可以在哪里打电话? await calculating_jaas_builds_count(); 来自 ngOnit()?
  • 这由您决定,我不知道您如何在应用程序中使用该值。 ngOnInit 可以是异步的,您可以在其中等待 promise,但请注意 Angular 不会延迟组件的初始化。 ngOnInit 的承诺将被忽略。但是,如果您尝试在组件中显示计数,那么我会建议采用完全不同的方法并将 this.totalbuilds_overview_jaas 设为 Observable,然后使用组件中的 async 管道绑定到它。然后您可以使用管道 @987654331使用 RXJS 运算符将 @ 转换为 this.totalbuilds_overview_jaas
猜你喜欢
  • 2019-09-29
  • 1970-01-01
  • 2016-07-10
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多