For code shortness I'm trying to store some similar functions inside an array, and call the correct function depending on a numeric key.
Each function returns a Promise, that actually wraps an Observable, I'm fecthing some data and pushing it to the corresponding data array. Calling each individual functions works fine, but when I'm trying to call them from the functions array (event based call), the "this' keyword refers to the function array instead of the class.
Here is the code:
public currentKey = 0;
...
constructor(private api: ApiService) {
}
ngOnInit() {
this.loadTrending(0); //THIS WORKS!
this.loadNews(0);
....
this.loadingMethods = [this.loadTrending, this.loadNews, this.loadCrowdfunding, this.loadUpcoming]
}
loadData(event) {
this.loadingMethods[this.currentKey](this.offsets[this.currentKey]).then(bool => {
event.target.complete(); // THIS DOESN'T WORK
});
}
public loadTrending(offset: number): Promise<boolean> {
return new Promise((resolve, reject) => {
this.api.trending(offset).subscribe(trending => { //'THIS' REFERS HERE TO THE ARRAY
this.gameLists[this.TRENDING_KEY].push(...trending.list);
resolve(true);
});
});
}
Is there a way to achieve this function call and have this refering to the class as usual ?
EDIT : I'm already using ECMA6 arrow functions that works througout all my project, so I don't think How to access the correct `this` inside a callback? is the answer here. Even though it is well explained there.
Error is:
core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'trending' of undefined
TypeError: Cannot read property 'trending' of undefined
at news.page.ts:68
at new ZoneAwarePromise (zone.js:910)
Thanks.