When attempting to retrieve an array of objects from the ngrx Store and assign it to an array using the subscribe option provided by Observables in Angular 2, an issue arises when trying to access the contents of the array. Below is a snippet of the code:
metaData$: Observable<MetaClassDefinition[]>;
myArray: MetaClassDefinition[] = [];
constructor(private store: Store<fromRoot.State>) {
this.metaData$ = store.select(fromRoot.getMetadata);
}
this.metaData$.subscribe(
data => {
if (data.length > 0) {
// Deep copy array
data.forEach(v => this.myArray.push({...v}));
}
},
error => { console.log(error)}
);
console.log(this.myArray); //-------(1)
console.log(this.myArray.length); //-------(2)
When the 1st console.log is executed, the array of objects is printed like this:
https://i.sstatic.net/bEpBz.png
However, when attempting to print the 2nd console.log, the size of the array is shown as zero. Is there something missing from this code that I am overlooking?