gpt4 book ai didi

javascript - 如何从 Javascript 回调方法调用 Typescript 方法 - Angular2

转载 作者:行者123 更新时间:2023-12-03 05:11:11 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com