[英]How can I pass an Angular2 method in my component as the callback method of a third party library?
I've got an Angular2 application that references a third party library. 我有一个引用第三方库的Angular2应用程序。 I reference that library in one of my components via: 我通过以下方式在我的组件之一中引用该库:
declare var thirdPartyLib: any;
Next I bind a button's click to the method below. 接下来,将按钮的单击绑定到以下方法。
buttonClick() { thirdPartyLib.open({ url: '{url goes here}', messageListener: function(eventData) { this.processResponse(eventData); } }); } processResponse(eventData: any) {...}
The problem is that when it fires the messageListener function I get an error that it "can't read property processResponse of undefined." 问题是,当它触发messageListener函数时,我收到一个错误,它“无法读取未定义的属性processResponse”。 I understand that there is an issue of scoping to 'this', but how do I call that method on my component from within that function? 我了解存在对“ this”进行范围界定的问题,但是如何从该函数中在我的组件上调用该方法? Or is there another way completely to do something like this? 还是有另一种完全可以做这种事情的方法?
Just for completeness, I've also attempted the following: 为了完整起见,我还尝试了以下操作:
buttonClick() { var myMethod = this.processResponse; thirdPartyLib.open({ url: '{url goes here}', messageListener: myMethod }); } processResponse(eventData: any) {...}
The problem with this method is that processResponse
calls a service as this.someService.whatever(eventData.something);
此方法的问题在于processResponse
将服务称为this.someService.whatever(eventData.something);
. 。 Using this approach throws the same error but now for this.someService
. 使用此方法会引发相同的错误,但现在会引发this.someService
。
Thanks in advance for the help! 先谢谢您的帮助!
I think, you have two options. 我认为,您有两种选择。
1. Arrow functions 1. 箭头功能
They will preserve the reference to current object in this
. 他们将在this
保留对当前对象的引用。
buttonClick() {
thirdPartyLib.open({
url: '{url goes here}',
messageListener: (eventData) => {
this.processResponse(eventData);
}
});
}
processResponse(eventData: any) {...}
Or even shorter form: messageListener: eventData => this.processResponse(eventData)
或更短的形式: messageListener: eventData => this.processResponse(eventData)
2. "that" pattern 2.“那个”模式
that
(or differently named) variable may hold reference to current object. that
(或不同地命名)变量可保持参照当前对象。
buttonClick() {
const that = this;
thirdPartyLib.open({
url: '{url goes here}',
messageListener: function(eventData) {
that.processResponse(eventData);
}
});
}
processResponse(eventData: any) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.