javascript - 异步调用

标签 javascript angular

我正在尝试在 extractContractsView 中调用此函数。

public getInsurantOrBeneficiary(content_type: number, object_id: number) {
    if (content_type == 25) { 
      this.http.get(AppSettings.API_ENDPOINT + '/api/v1/artifical_persons' + "/" + object_id + "/", this.options)
        .map((response: Response) => response.json())
        .subscribe((result: any) => {
          this.data_name = result;
          this.name = this.data_name['name'];
          console.log('Artifical persons' + this.name);
          return this.name;
        });
    } else if (content_type == 12) { 
      this.http.get(AppSettings.API_ENDPOINT + '/api/v1/private_persons' + "/" + object_id + "/", this.options)
        .map((response: Response) => response.json())
        .subscribe((result: any) => {
          this.data_private_persons = result;
          this.id_private_persons = this.data_private_persons['passport_id'];
          console.log('id_private_persons:' + this.id_private_persons);
        });

        this.http.get(AppSettings.API_ENDPOINT + '/api/v1/passports' + "/" + this.id_private_persons + "/", this.options)
        .map((response: Response) => response.json())
        .subscribe((result: any) => {
          this.data_name = result;
          this.name = this.data_name['second_name'] + ' ' + this.data_name['first_name'] + ' ' + this.data_name['paternal_name'];
          console.log('Name in passport:' + this.name);
          return this.name;
        });
    } else if (content_type == 43) { 
      this.http.get(AppSettings.API_ENDPOINT + '/api/v1/sole_proprietorship' + "/" + object_id + "/", this.options)
        .map((response: Response) => response.json())
        .subscribe((result: any) => {
          this.data_name = result;
          this.name = this.data_name['name'];
          console.log('sole_proprietorship' + this.name);
          return this.name;
        });
    }
    return this.name;
  }

问题是,当我调用 getInsurantOrBeneficiary 函数时,我仅在第一次迭代时获取数据。但 content_type [i] 和 object_id [i] 总是不同的,我希望函数返回不同的 this.name。 我不太了解异步的工作,可能 this.http.get 没有时间工作,我只得到一次答案。

 public extractContractsView = (response: Response) => {

    let res = response.json();
    let contracts: ContractsView[] = [];

    for (let i = 0; i < res.length; i++) {

      let insurant = this.getInsurantOrBeneficiary(res[i].insurant_id.content_type, res[i].insurant_id.object_id);
      let beneficiary = this.getInsurantOrBeneficiary(res[i].beneficiary_id.content_type, res[i].beneficiary_id.object_id);

      contracts.push(new ContractsView(
        res[i].id,
        res[i].treaty_number,
        res[i].days_left,
        res[i].days_left_before_the_next_payment,
        res[i].payment_status_KB,
        res[i].security_deposit_no_deposit,
        res[i].currency_conversion_only,
        res[i].currency,
        res[i].contact,
        res[i].additional_information,
        res[i].prolongation,
        res[i].improving_conditions,
        res[i].redundancy,
        res[i].akt_on_KB,
        res[i].payment_status_akt_on_KB,
        insurant,
        beneficiary,
        res[i].insurance_type_id.name,
        res[i].insurer_id.name,
        res[i].executor_id,
        res[i].status,
        res[i].payment,
        res[i].time_of_action.date_start + ' - ' + res[i].time_of_action.date_end,
        res[i].finance,
        res[i].date,
        res[i].subagent,
        res[i].insurance_object,
      ));    
    }
    return contracts;
  }

  public getContracts(): Observable<ContractsView[]> {
    let contracts = this.http.get(this.url, this.options)
      .map(this.extractContractsView)
      .catch(this.handleError);
    return contracts;
  }

感谢您的帮助。

最佳答案

您将需要重构 API get 调用以返回可观察对象并在使用函数中订阅它们。您每行进行两次 API 调用。您可以使用 ForkJoin 运算符组合两次调用的结果,然后完成插入到新数组中。我正在缩写代码。这应该会让您朝着正确的方向前进。

    public getInsurantOrBeneficiary(content_type: number, object_id: number): Observable<any> {
        if (content_type == 25) { 
          // Return an observable, do not subscribe here
          return this.http.get(endpoint, options)
            .map((response: Response) => response.json());
        }
    }

然后在这里订阅并处理:

public extractContractsView = (response: Response) => {

    let res = response.json();
    let contracts: ContractsView[] = [];

    for (let i = 0; i < res.length; i++) {

// Use a forkJoin to combine the results of 2 or more observables
forkJoin(
    this.getInsurantOrBeneficiary(),
    this.getInsurantOrBeneficiary()
)
.subscribe((result1: any, result2: any) => {
    contracts.push(new ContractsView(result1, result2))
});
}

请注意,循环将在所有异步结果返回之前完成。正如评论中指出的,这可能不是最好的方法。但是,使用这种方法可以实现您想要做的事情。

关于javascript - 异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52193766/

相关文章:

javascript - JavaScript 中的方法链接失败

javascript - Angular typeScript嵌套数组不可迭代?

javascript - jQuery .on ('click) not working on elements loaded throught .load(' lorem.php')

javascript - Array.any 的等价物是什么?在 JavaScript 中?

javascript - 使用 Js 或 jquery 更改具有不同时间间隔的图像

javascript - 在输入字段中的文本输入后添加单位 Angular 5

angular - Jasmine 在所有测试通过后抛出错误

angular - 扩展 Angular2 组件装饰器

javascript - 为什么 ngOnChange 没有检测到 @Input 元素更改而 ngOnDetect 能够这样做

javascript - jstree 类型插件不显示自定义图标