首页 > 解决方案 > 如何将方法中的数据存储到角度数组中?

问题描述

在我的组件中,我有一个方法可以从我的 API 中检索数据,如下所示:

export class OrderExceptionReportComponent implements OnInit {

  public sessionData: ExceptionReportSessionData[] = [];

  constructor(private orderExceptionReportService: OrderExceptionReportService) {
  }

  public async getExceptionReportSessionData(): Promise<void> {
    this.orderExceptionReportService.GetExceptionReportSessionData()
      .then(
        data => {
          this.sessionData = data;              
        });

  }
ngOnInit() {
    this.getExceptionReportSessionData();
    console.log(this.sessionData);
  }

我正在尝试将检索到的数据存储到sessionData数组中,这样我就可以将这些数据用于我想要实现的几个过滤器。调用时console.log(this.sessionData);,数组在控制台中显示为未定义。

如何将数据存储getExceptionReportSessionData()到数组中,以便访问组件其他部分的数据?

标签: javascriptangulartypescript

解决方案


上面的代码似乎有两个错误。您没有从该方法返回承诺,也没有等待该承诺的响应。

假设在您的实施中没有其他并发症OrderExceptionReportService,以下应该可以解决您的问题。

    export class OrderExceptionReportComponent implements OnInit {

      public sessionData: ExceptionReportSessionData[] = [];

      constructor(private orderExceptionReportService: OrderExceptionReportService) {
      }

      public getExceptionReportSessionData(): Promise<void> {
        return this.orderExceptionReportService.GetExceptionReportSessionData()
          .then(
            data => {
              this.sessionData = data;              
            });

      }
    ngOnInit() {
        await this.getExceptionReportSessionData();
        console.log(this.sessionData);
      }

推荐阅读