There are 2 instances of Array<object>
. One of them contains initial elements, while the other has elements added using array.push()
within ngOnInit
. Despite both arrays having the same elements in their output, the rendered html does not display the elements that were pushed with .push
.
// Resulting array created by array.push()
> []
> 0: {id: '1', title: 'title 1'}
> 1: {id: '2', title: 'title 2'}
> 2: {id: '3', title: 'title 3'}
length: 3
> __proto__: Array(0)
// Initializing array
> (3) [{…}, {…}, {…}]
> 0: {id: '1', title: 'title 1'}
> 1: {id: '2', title: 'title 2'}
> 2: {id: '3', title: 'title 3'}
length: 3
> __proto__: Array(0)
The code snippet:
newObj;
error;
myObjects: Array<object> = [];
itsObjects: Array<object> = [
{
id: '1',
title: 'title 1'
},
{
id: '2',
title: 'title 2'
},
{
id: '3',
title: 'title 3'
}
];
ngOnInit() {
this.subscription = this.mys.myService().subscribe(
res => {
this.newObj = res,
this.myObjects.push(
{
id: element.id,
title: element.title
}
)
},
error => this.error = error,
)
}
Solution
The key observation was the line this.myObjects = this.tmpObj
after the forEach
loop, which collects all elements to pass outside the scope of ngOnInit
. The updated code now reads:
servicOutput; // Get data
tmpObj: Array<object> = []; // Manage data as temp
myObjects: Array<object> = []; // Collect all elements for rendering in HTML
error;
ngOnInit() {
this.subscription = this.mys.myService().subscribe(
res => {
this.servicOutput = res,
this.servicOutput.forEach(element => {
this.pushFunc(element);
}
),
this.myObjects = this.tmpObj; // Collect and pass all elements as an object out of ngOnInit scope
},
error => this.error = error,
)
}
pushFunc(element) {
this.tmpObj.push(
{
id: element.id,
title: element.title
}
)
}