In Angular 7, I'm passing arrays of person objects from the parent component to the child component. In the parent component the data is retrived by calling the rest endpoint of a user id list:
....forEach(userId => {
this.api.getUser(userId).subscribe((personDto: PersonDTO) => {
this.personList.push(personDto);
}
}
When the child component is loaded the full person list is not retrieved yet. Therefore I defined an BehaviourSubject in the Child Component.
Parent component:
<app-child-component [data]="personList"></app-child-component>
Child component:
private _data = new BehaviorSubject<PersonDTO[]>([]);
@Input()
set data(value: PersonDTO[]) {
this._data.next(value);
};
get data() {
return this._data.getValue();
}
ngOnInit() {
console.log(this.data);
}
In the ngOnInit function in my child component I expect to get an array of PersonDto's. In the console I can see that I get the correct expected list of persons. But the problem is that the output in the console looks like this:
[]
0 Object { id: 1, username: "John", ... }
1 Object { id: 2, username: "Peter", ... }
length: 2
<prototype>: []
It has allways an array where the first element is [] an in this elment I can see the array with the correct values. I think the [] comes from my initialization:
private _data = new BehaviorSubject<PersonDTO[]>([]);
How can I get the array that it only contains the 2 values? I already tried with this.data[0]. But then I get an undefined. Any ideas?
this.data.lengthandthis.data[0]?