I have 2 Array<object>
. One of them has initial elements and another one has its elements added by array.push()
in ngOnInit
. In the end, both have the elements in output but html doesn't render the elements which were pushed with .push
//the result of array that made 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)
//initialize 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
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,
)
}
Solved
The main notice was this.myObjects = this.tmpObj
after forEach
that collects all elements for pass to out of ngOnInit
scope, I edited my code to:
servicOutput; //get data
tmpObj: Array<object> = []; //manage data as temp;
myObjects: Array<object> = []; //for collect all elements to html
error;
ngOnInit() {
this.subscription = this.mys.myService().subscribe(
res => {
this.servicOutput = res,
this.servicOutput.forEach(element => {
this.pushFunc(element);
}
),
this.myObjects = this.tmpObj; //here collect all elements as an object and pass out of ngOnInit scope
},
error => this.error = error,
)
}
pushFunc(element) {
this.tmpObj.push(
{
id: element.id,
title: element.title
}
)
}