One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data.
The problem arises when attempting to use the callback function to append the fetched data to an existing variable in the component. An
EXCEPTION: TypeError: Cannot read property 'messages' of undefined
is encountered. Why is this
undefined?
TypeScript version being used: 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
})
}
}