Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  145] [ 7]  / answers: 1 / hits: 63902  / 8 Years ago, thu, july 7, 2016, 12:00:00

I have a component which calls a service to fetch data from a RESTful endpoint. This service needs to be given a callback function to execute after fetching said data.



The issue is when I try use the callback function to append the data to the existing data in a component's variable, I get a EXCEPTION: TypeError: Cannot read property 'messages' of undefined. Why is this undefined?



TypeScript version: Version 1.8.10



Controller code:



import {Component} from '@angular/core'
import {ApiService} from '...'

@Component({
...
})
export class MainComponent {

private messages: Array<any>;

constructor(private apiService: ApiService){}

getMessages(){
this.apiService.getMessages(gotMessages);
}

gotMessages(messagesFromApi){
messagesFromApi.forEach((m) => {
this.messages.push(m) // EXCEPTION: TypeError: Cannot read property 'messages' of undefined
})
}
}

More From » arrays

 Answers
97

Use the Function.prototype.bind function:



getMessages() {
this.apiService.getMessages(this.gotMessages.bind(this));
}


What happens here is that you pass the gotMessages as a callback, when that is being executed the scope is different and so the this is not what you expected.

The bind function returns a new function that is bound to the this you defined.



You can, of course, use an arrow function there as well:



getMessages() {
this.apiService.getMessages(messages => this.gotMessages(messages));
}


I prefer the bind syntax, but it's up to you.



A third option so to bind the method to begin with:



export class MainComponent {
getMessages = () => {
...
}
}


Or



export class MainComponent {
...

constructor(private apiService: ApiService) {
this.getMessages = this.getMessages.bind(this);
}

getMessages(){
this.apiService.getMessages(gotMessages);
}
}

[#61476] Tuesday, July 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;