嵌套在http请求中时,角度4函数未定义 [英] angular 4 function undefined when nested in http request
问题描述
我是新手,尝试快速学习,但是对于发生的事情我感到困惑.加载我的TS文件时,它会从http.get请求中获取消息列表,并将它们存储在变量conversation
中.但是,当我添加一条新消息时,它就是将其添加到我的API中并返回结果,但是当我尝试将消息添加到对话中时,却收到了错误消息
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未定义
this.insertMessage is undefined
但是功能已设置.请参阅下面的代码.我假设当您尝试在.subscribe方法中的complete函数中调用函数时,您无法访问外部函数.正确吗?
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');
}
}
推荐答案
使用更现代的箭头函数(() => {}
)语法代替 old 常规函数语法(function () {}
)保留this
的范围.
Use the more modern arrow functions(() => {}
) syntax instead of the old normal functions syntax(function () {}
) to retain the scope of this
.
由于this
的范围在您的回调函数中已更改,所以this
不再引用您的MessagePage
.
Since the scope of this
changed in your callback function, this
was not referring to your MessagePage
anymore.
使用箭头函数(() => {}
)语法将保留this
的范围.
Using the arrow functions(() => {}
) syntax will retain the scope of this
.
使用此修补程序:
addmessage(): void {
this.messageService.addMessage(this.newmessage, this.id)
.subscribe(
response => this.response = response,
error => console.log("Error happened" + error),
() => {
if (this.response.result == 200)
this.insertMessage(this.response.response.message);
else console.error(this.response);
}
);
}
这篇关于嵌套在http请求中时,角度4函数未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!