What is the right way to wait for data in Angular?

I have a child-component `CheckboxListComponent` which shows a list of checkboxes. The list is populated in `ngOnInit` through a webservice-call which takes more or less time. It also has a function `setEntryChecked` to set a specific item to checked. When `foo()` is called before the `CheckboxListComponent` has it’s data the call was lost or has no effect. My solution is to wait for the result to be available with `await this.listSubject.first().toPromise()`. Is there a better way to do this in TypeScript? “`ts export class MainComponent { @ViewChild(‘checkboxList’) checkboxListComponent: CheckboxListComponent; foo() { this.checkboxListComponent.setEntryChecked(…, true); } } export class CheckboxListComponent implements OnInit { list: []; private listSubject = new Subject(); async ngOnInit() { try { this.list = await this.dataService.get(‘url’); this.listSubject.next(true); } catch (err) { this.listSubject.next(false); } this.listSubject = undefined; } async setEntryChecked(name: string, isChecked: boolean) { // wait for the list to be initialized if (this.listSubject) { await this.listSubject.first().toPromise(); } // make the item checked } } “`

Leave a Reply

Your email address will not be published. Required fields are marked *