Specify this context
I support Blindman67's answer. If arrow functions were not supported by all browsers used (e.g. IE - but then again there is little support for Angular in IE anyway) then you could also utilize Function.bind():
this.$onInit = function() {
const id = $route.current.params.someId;
this.documents = [];
myFactory.getData(id).then((response) => {
response.documents.forEach((object) => {
this.documents.push(object);
}.bind(this));
}
}
Or utilize the second parameter of Array.foreach() (i.e. thisArg):
this.$onInit = function() {
const id = $route.current.params.someId;
this.documents = [];
myFactory.getData(id).then((response) => {
response.documents.forEach((object) => {
this.documents.push(object);
}, this);
}
}
Avoid the looping
Even simpler would be to push all items with the spread operator, since Array.push() can accept a variable number of elements:
this.$onInit = function() {
const id = $route.current.params.someId;
this.documents = [];
myFactory.getData(id).then(response => this.documents.push(...response.documents));
}
Because ...response.documents will spread the arguments out to match the parameters (i.e. element1[, ...[, elementN]]).
That way there is no need to iterate over the items. Array.concat() could also be used but then the array would need to be re-assigned. Or Array.unshift() could also be used with the spread operator.
Expand the snippet below for a demonstration (AngularJS code removed for simplicity).
const documents = [];
const id = 3;
const myFactory = {
getData: function(id) {
const newDocuments = [1,2,3];
return new Promise(function(resolve, reject) {
setTimeout(resolve, 750, {"documents": newDocuments});
});
}
};
console.log('original documents',documents);
myFactory.getData(id).then(function(response) {
documents.push(...response.documents);
console.log('documents after push',documents);
})