【问题标题】:Angular Using Promises and Async FunctionsAngular 使用 Promise 和异步函数
【发布时间】:2021-06-28 12:37:45
【问题描述】:

我正在尝试从一个 http 请求中检索数据。在这个操作之后,我用响应填充我的变量。 我在第二个函数中使用该变量来填充我的表单。我所需要的只是第二个函数必须等待第一个函数完成其周期。 我在这里做错了什么?


下面是我的代码:

spec-component.ts

  async init() {
    await this.getBaseSpecs();
    await this.matchOfferingModelSpecifications(this.baseSpecList, this.offeringModel);
  }


      getBaseSpecs() {
    this.specificationService.getAllSpecifications('offeringBase').toPromise().then((specificationList) => {
      if (specificationList && specificationList.length > 0) {
        this.baseSpecList = specificationList[0].parameters;
      }
    });
  }

  matchOfferingModelSpecifications(parameterList: ParameterModel[], offeringModel: OfferingModel) {
    const resultParameterList: ParameterModel[] = [];
    for (const offeringParameter of offeringModel.specifications[0].parameters) {
      for (const defaultParameter of parameterList) {

        if (offeringParameter.name === defaultParameter.name) {
          resultParameterList.push(offeringParameter);
        }
        this.modalForm.addControl(offeringParameter.name, new FormControl(offeringParameter.value.toString()));

      }
    }

    offeringModel.specifications[0].parameters = resultParameterList;
  }

spec-service.ts

  getAllSpecifications(specName: string) {
    return this.http.get<SpecificationModel[]>(`${environment.api_url}/specification?specName=${specName}`);
  }

【问题讨论】:

    标签: angular async-await promise


    【解决方案1】:

    你所有的尝试都是正确的。

    async doAll() {
      try {
        const res = await this.service.getAllSpecifications(name).toPromise();
        const basicList =  res[0].parameters;
        // do your second function.
      } catch (e) {
      } finally {
      }
    }
    
    // and call this function from ngOnInit()
    

    也许这是更易于人类阅读的代码...

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 2019-05-27
      • 2021-02-15
      • 2020-08-13
      • 2019-04-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      相关资源
      最近更新 更多