I am new to angular and trying to learn quickly but I am stumped as to what is happening. When my TS file is loaded, it gets a list of messages from a http.get request and stores them int he variable conversation
. However, when I add a new message, it is making it to my API and returning a result, but when I try to add the message to the conversation, I get the error
this.insertMessage is undefined
But the function is set. See code below. I assume that when you are trying to call a function within the complete function in the .subscribe method, you cannot access external functions. Is that correct?
export class MessagePage {
newmessage;
conversation;
id;
response: {};
ionViewWillEnter(){
this.getMessage(this.id);
}
// public messageArr;
constructor(public navCtrl: NavController, public navParams: NavParams, public messageService: MessagesProvider) {
this.id = navParams.get('id');
}
addmessage(): void {
this.messageService.addMessage(this.newmessage,this.id)
.subscribe(
function(response) { console.log("Success Response" + response); this.response = response;},
function(error) { console.log("Error happened" + error)},
function() {
if(this.response.result == 200) this.insertMessage(this.response.response.message);
else console.error(this.response);
}
);
}
getMessage(id: number): void {
this.messageService.getMessage(id)
.subscribe(message => this.conversation = message);
}
insertMessage(message): void {
console.log('conversation:'+ this.conversation);
this.conversation.push(message);
}
ionViewDidLoad() {
console.log('ionViewDidLoad MessagePage');
}
}