Angular(8)-Foreach循环调用subscribe和ForkJoin(请参阅说明)[重复]

问题描述 投票:0回答:2

此问题已经在这里有了答案:

[我正在做的是在对象的foreach上进行一个array循环,在每个这些对象上,我正在调用订阅API。我的问题是,我不断在对象控制台日志中获取带有该值的“ _zone_aware_promise”,但我无法访问它。我已经在函数中尝试了async-await之类的方法,但是由于在下面简化了我的代码,因此未包含在其中:

// Method call
nonEmployeeValidation( employees: any ) {

  employees.forEach(element => {
    element.manager = this.api_validation(element.manager)
  });

  // My loop is done i've formatted my object good to go from here
  this.someMethodCallForFurtherLogic(employees)

}

// Api call
api_validation( manager: string ) {

   // This goes to the service I built basically its just an HTTPCLIENT POST METHOD
   this.employeeService.managerValidation(manager)
          .subscribe((res: APIResponse<any>) => {
           return res.isValid;
   });

}

请在这方面指导我。

谢谢

angular foreach rxjs subscribe fork-join
2个回答
0
投票

您只是不能直接从可观察对象返回值,因为它发出多个异步调用。异步调用意味着在代码继续执行的同时,它正在后台运行(实际上已安排在以后执行)。但是,您可以使用来自订阅的响应并将其设置为变量。

   nonEmployeeValidation( employees: any ) {

      employees.forEach(employee => {
         this.api_validation(employee)
      });

      this.someMethodCallForFurtherLogic(employees)

    }

    // Api call
    api_validation( employee: any ) {

       this.employeeService.managerValidation(employee.manager)
              .subscribe((res: APIResponse<any>) => {
               employee.manager = res.isValid;
       });

    }

0
投票

您可以将employees数组映射到验证调用的数组,然后使用CombineLatest使单个可观察对象发出所有验证调用结果的数组。 validateResults将匹配原始的雇员数组。

combineLatest(employees.map(employee => this.employeeService.managerValidation(employee.manager)))
  .subscribe(validationResults => {
    // Here you have an array of the results for each validation call
    validatedEmployees = employees.map((e, index) => ({...e, manager: validationResults[index].isValid }))
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.