admin管理员组文章数量:1406060
I'm trying to make an application with Angular 2. Now I ran into a problem which I can't solve.
One of the functions of an array should be push(object: T);
I defined an array of an object that I made. But when I try to add values to this array I receive the following error: TypeError: Cannot read property 'push' of undefined.
One of the main causes of this error is people forgetting to define their array. But I'm defining it, I tried it in multiple ways but still the same error.
export class Home {
activeDossiers: Array<Dossier> = new Array();
//Also tried:
//activeDossiers: Dossier[] = [];
//activeDossiers = [];
//activeDossiers: Array<Dossier> = [];
constructor() {
var dossierApi = new DossierApi();
dossierApi.getActiveDossiers().then((dossiers) => {
dossiers.forEach(function (obj, i) {
console.log(obj);
if(obj.dossierType === Values.Visible) {
this.activeDossiers.push(obj);
}
});
});
}
}
I'm trying to make an application with Angular 2. Now I ran into a problem which I can't solve.
One of the functions of an array should be push(object: T);
I defined an array of an object that I made. But when I try to add values to this array I receive the following error: TypeError: Cannot read property 'push' of undefined.
One of the main causes of this error is people forgetting to define their array. But I'm defining it, I tried it in multiple ways but still the same error.
export class Home {
activeDossiers: Array<Dossier> = new Array();
//Also tried:
//activeDossiers: Dossier[] = [];
//activeDossiers = [];
//activeDossiers: Array<Dossier> = [];
constructor() {
var dossierApi = new DossierApi();
dossierApi.getActiveDossiers().then((dossiers) => {
dossiers.forEach(function (obj, i) {
console.log(obj);
if(obj.dossierType === Values.Visible) {
this.activeDossiers.push(obj);
}
});
});
}
}
Share
Improve this question
asked Dec 8, 2015 at 10:01
StefanStefan
971 silver badge6 bronze badges
0
1 Answer
Reset to default 4You are using the anonymous function()
syntax for the callback; this syntax does NOT preserve the this
. Instead do:
dossiers.forEach((obj, i) => { // IMPORTANT PART HERE!!!
console.log(obj);
if(obj.dossierType === Values.Visible) {
this.activeDossiers.push(obj);
}
});
本文标签: javascriptTypeScript TypeError Cannot read property 39push39 of undefinedStack Overflow
版权声明:本文标题:javascript - TypeScript: TypeError: Cannot read property 'push' of undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744964975a2634890.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论