Reputation: 2023
I have declared a person object and defined some arrays in constructor. I am calling a method in init method to get all the races. But I am getting undefined error message in the line "this.person.races.push($(val).attr("title"));" even though I have declared it in constructor.
export class PersonInvolvedComponent {
person = {}
constructor(private _globalService:GlobalService) {
this.person = {
races: [],
gender: [],
builds: [],
eyeColors: [],
hairColors: []
}
}
ngOnInit() {
this._globalService.applyLanguage("xml/"+this._globalService.getLanguage()+".xml");
this.appendRace();
this.appendGender();
this.appendBuild();
this.appendEyeColor();
this.appendHairColor();
}
appendRace(){
var config = this._globalService.loadConfiguration('config/personConfig.xml');
config.subscribe(
data => {
$(data._body).find("racename").each(function(i,val)
{
this.person.races.push($(val).attr("title"));
}
)},
err => console.error(err),
() => console.log('done')
);
}
}
Upvotes: 1
Views: 419
Reputation: 1364
Modify your call to .each like this :
config.subscribe(
data => {
$(data._body).find("racename").each((i,val) =>
{
this.person.races.push($(val).attr("title"));
}
)},
err => console.error(err),
() => console.log('done')
);
Calling a anonymous function by using the keyword function
unscope this
; using lambda you don't and this
still represent your class
Upvotes: 3