【问题标题】:Angular Promise don't work : ERROR TypeError: DataSource is undefinedAngular Promise 不起作用:错误类型错误:数据源未定义
【发布时间】:2021-05-31 20:17:00
【问题描述】:

我在等待填充数据源时遇到问题:

HTML

<app-single-y-axis [xAxysDataSource]="dataSource['labels']"
                   [yAxysDataSource]="dataSource['series']">
</app-single-y-axis>

组件.TS

ngOnInit(): void {
  this.getData();
}

getData = async () => {
  this.dataSource = await this.dataService.getDataAnalysis();
}

我也尝试(但得到了相同的结果):

 getData = async () => {
     this.dataService.getDataAnalysis()
      .then (res => {
          this.dataSource = res;
      })
    })
 }

数据服务

getDataAnalysis = async () => {
  return new Promise((resolve, reject) => {
     do something...
     this.anotherService.deviceDataAnalysis()
       .then(analysisRes => { i'll do what i have to do and works}
     }
  })
}

另一种服务

deviceDataAnalysisPromise() {
return this.http.post(BACKEND_URL + "url")
  .pipe(map((res: any) => {
    return res;
  })).toPromise();

问题是当我运行它时,在控制台日志中我有

ERROR TypeError: ctx_r31.dataSource is undefined 

提到 HTML,3 / 7 次,这取决于,直到填充数据源...我不明白如何告诉他更好地等待所有人的响应,然后开始恐慌...

很明显,当填充数据源时一切正常

有人可以帮我吗???

【问题讨论】:

    标签: angular async-await promise undefined angular-promise


    【解决方案1】:

    getDataAnalysis 返回的承诺永远不会得到解决。 而不是创建new Promise(),您可以简单地返回您已经拥有的:

    getDataAnalysis = async () => {
      return this.anotherService.deviceDataAnalysis()
           .then(analysisRes => { return "i'll do what i have to do and works"});
    }
    

    【讨论】:

    • 谢谢,但是......它不起作用:(......它总是不等待它并打印 ERROR TypeError: ctx_r32.dataSource is undefined
    【解决方案2】:

    这样解决

    HTML

    <span *ngIf="DataSourceDefined">
    

    在我的组件中,当它接收到数据源时,我将 DataSourceDefined = true...

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 2019-07-20
      • 1970-01-01
      • 2019-06-20
      • 2020-09-09
      • 2019-10-31
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多