【发布时间】:2018-10-12 15:56:42
【问题描述】:
我是 Angular 的新手,并试图快速学习,但我对正在发生的事情感到困惑。当我的 TS 文件被加载时,它会从 http.get 请求中获取消息列表并将它们存储在变量 conversation 中。但是,当我添加一条新消息时,它会发送到我的 API 并返回结果,但是当我尝试将消息添加到对话中时,我会收到错误
this.insertMessage 未定义
但是功能已经设置好了。请参阅下面的代码。我假设当您尝试在 .subscribe 方法的完整函数中调用函数时,您无法访问外部函数。对吗?
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');
}
}
【问题讨论】:
标签: angular ionic-framework ionic3