【问题标题】:How to call parent function from callback function in angular 2?如何从角度 2 中的回调函数调用父函数?
【发布时间】:2018-03-20 09:28:54
【问题描述】:
这是一个类
export class ChatDetailPage {
constructor(){
}
funcA(){
var options = {
onSubmit: function (text) {
//i want to be able to access funcB from here
this.funcB(text)
},
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}
}
在这种情况下,我如何从 Anular 2 或 Ionic 3 中的 onsubmit 回调函数调用 funcB。
提前致谢。
【问题讨论】:
标签:
angular
typescript
ionic2
ionic3
angular2-components
【解决方案1】:
使用箭头函数,捕获this的值:
export class ChatDetailPage {
constructor(){
}
funcA(){
var options = {
onSubmit: text => {
//i want to be able to access funcB from here
this.funcB(text)
},
};
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}
}
【解决方案2】:
有时您将无法使用箭头功能,例如。当它是内置或库函数时。在这种情况下,您可以使用的解决方案是将 this 变量绑定到名为 self 的变量或任何您想要的变量。
funcA(){
// bind the this variable to 'self' outside of the function scope
var self = this;
var options = {
onSubmit: function (text) {
// and use self instead of this
self.funcB(text)
},
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}