I need to do next one - get data from backend and forward it to child component:
...
@Component({
selector: 'my-component',
template: `<my-child-component [data]="data"></my-child-component>`
})
public data = [];
ngOnInit() {
this.service.getParentData().subscribe(res => {
res.map(r => this.service.getChildDatas(r.id)
.subscribe(child => this.data.push(child)));
});
}
But in a child component, when I try to print data in ngOnChanges, I see just strange array, I can see elements, but length is equal to 0:
How does it work and how can I achieve my objective (pass data to child and work with data as with array)?
You seems to have 2 observables that you want to pipe, the one after the other. You'll need to use rxJS operators to achieve that.
The way to achieve it is to use operator switchMap, or mergeMap depending if you want the changes of the first to re-trigger the second one.
Then use forkJoin operator, to subscribe to a list of observable and threat results as a list
Assuming that you receive an array first, and need for each array value to get the child one through another service you'll have
ngOnInit() {
this.service.getParentData()
.pipe(switchMap((parentData: {id: string}[]) => {
return forkJoin(parentData.map(r =>
this.service.getChildDatas(r.id))
})
.subscribe((childData: any[]) => {this.data = childData});
}