我正在使用 angular2,我的问题是我无法从 javascript 回调调用组件方法,这里是代码片段。
declare var CORE_FACTORY:any;
// CORE_FACTORY Defined in javascript file which I've included in index.html and it's gets loded perfectly.
let coreApi = CORE_FACTORY.setupApiByDomain(Domain.QA);
coreApi.addUserEventListener(apiName, ApiEvent.ON_ANY_EVENT,this._userCallBack);
coreApi.callApi(request, this.afterCallApi);
afterCallApi(status, responceObject) {
this.postCreateInstrument(accountNumber); //Getting error right here.
}
public postCreateInstrument(accountNumber:string) {
alert('test');
}
最佳答案
访问全局的方式之一this
就是使用bind
像这样:
coreApi.callApi(request, this.afterCallApi.bind(this, status, responceObject));
现在这段js代码coreApi.callApi(request, this.afterCallApi);
如您所知,会调用 this.afterCallApi
但请注意,您使用的函数不带括号 () 这意味着 this.afterCallApi
将作为callApi
的内部函数被调用,与 callApi
的内心this
绑定(bind)到afterCallApi
。
如果你想测试它,请执行 console.log(this);
里面afterCallApi
用你原来的代码。你会看到this
是一个对象而不是全局 this
。
为了给予afterCallApi
“访问权”我们只是bind
this
指的是全局this
.
另请查看这篇精彩帖子以获取更多信息:How to access the correct `this` inside a callback?
关于javascript - 如何从 Javascript 回调方法调用 Typescript 方法 - Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41813102/