I have a parent that is getting data from a database by subscribing to an observable.
My problem is that I have a child component that is using the data from the parent component in its ngOnInit method. That creates an error since the data is not there yet when the child component is rendered.
In the following, I get the error because "disciplines", which I got from my observable hadn't been returned yet. But the child was rendered and the ngOnInit was accessing an empty array at this point.
This works fine if I hardcode disciplines with a value instead of waiting for the observable to return the data.
So the question is, how to make sure the data is in my variable before the ngOnInit of the child component accesses it.
In the Parent I have this in the ngOnInit method:
this.disciplines = [];
let getOptions = this.service.getOptions().subscribe((data: any) => {
this.populateOptions(data);
});
...
populateOptions(data: any): void {
this.disciplines = data['disciplines'];
}
In the parents template
<cmp-child
[disciplines]="disciplines"
</cmp-child>
In the ngOnInit of the child component,
ngOnInit(): void {
this.populateOptions()
}
populateOptions(): void {
this.advanced = this.disciplines.filter(d => d.isAdvancedDiscipline === true).map(m => m.id);
console.log("disciplines: ", this.disciplines);
}
Thanks,
Tom