Reputation: 987
I have a parent component that has a button when the user clicks it will make a request and passed the data into a child component (a ngx-bootstrap modal). The child component will use the async data to make another request to render its UI.
My parent component is like this:
<Parent>
<child-modal [subSectionInfo]="subSectionInfo"></child-modal>
</Parent>
the subSectionInfo is async data retrieved from an ajax in Parent component.
My child component will make call like this:
ngOnInit() {
const id = this.subSectionInfo.id;
this._fetchData(id)
}
private _fetchData(id: number) {
this.service
.getData(id).pipe(
.subscribe((data: any) => {
this.list = data;
});
}
However, this always gives me undefined which causes the child component ajax call failed. Is any way to solve this issue? Thank you so much in advance!
Upvotes: 0
Views: 263
Reputation: 325
Currently, your code does not wait on the first request to complete. While the request for subSectionInfo
is being made in the parent component, it's value is undefined since the value hasn't returned from the server yet. This is why the child component get's undefined
. There are 2 ways to approach this.
subSectionInfo
to your child component.ngOnChanges
life-cycle hook. This is where your child component implements OnChanges. You can read more about it here. ngOnChanges(changes: SimpleChanges) {
if (changes['subSectionInfo'].currentValue !== undefined) {
const id = this.subSectionInfo.id;
this._fetchData(id)
}
}
private _fetchData(id: number) {
this.service
.getData(id).pipe(
.subscribe((data: any) => {
this.list = data;
});
}
Hope this helps
Upvotes: 1