Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle async in ngOnChanges

Tags:

angular

I ran into this issue and I don't see how to treat async method because ngOnChanges doesn't support async.

What do you guys do to make this happen?

It doesn't work when I apply async to ngOnChanges. The return value is Promise.

@Component({
  moduleId: module.id,
  selector: 'search',
  templateUrl: 'search.template.html'
})
export class Search implments OnChanges {
  async queryArray(data: string): Promise<T> {
     //sample scripts.
     return ....;
  }
  ngOnChanges(changes: SimpleChanges) {
     let query: string = "red";
     let result: string[] = [];

     await this.queryArray(query).then(resp => result = resp);
  }

}

like image 372
fletchsod Avatar asked Jan 21 '26 03:01

fletchsod


1 Answers

  • Mark the method as async
  • Add await to wait for the result of the Promise
  • Remove the then as now you can assign the result directly once you add the await
  • Assign the result directly.

Code:

async ngOnChanges(changes: SimpleChanges) {
   let query: string = "red";
   let result: string[] = [];

   result = await this.queryArray(query);
}

Also note that queryArray does not need to be marked as async unless you want to also await the result in that method for further processing. If all it is doing is creating and returning a Promise then it is not necessary.

like image 163
Igor Avatar answered Jan 22 '26 19:01

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!