coeix
coeix

Reputation: 15

Angular Promise don't work : ERROR TypeError: DataSource is undefined

i have issue by waiting dataSource is populated:

HTML

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

COMPONENT.TS

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

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

i try also (but got the same result):

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

DATASERVICE

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

ANOTHERSERVICE

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

The problem is that when i run it, in console log i have

ERROR TypeError: ctx_r31.dataSource is undefined 

refered to HTML, for 3 / 7 time, it depends, until dataSource is populated... i don't understand how to tell him better to wait the response of all before start to go in panic...

Obviusly when dataSource is populated all works good

can someone help me please???

Upvotes: 0

Views: 343

Answers (2)

coeix
coeix

Reputation: 15

solved in this way

HTML

<span *ngIf="DataSourceDefined">

and in my component i put DataSourceDefined = true when it receive the dataSource...

Upvotes: 0

Martin Paucot
Martin Paucot

Reputation: 1251

Your promise returned by getDataAnalysis never get resolved. Instead of creating a new Promise() you could simply return the one you already have:

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

Upvotes: 1

Related Questions