Typescript/Angular - 模态结果返回后调用单独的函数

Posted

技术标签:

【中文标题】Typescript/Angular - 模态结果返回后调用单独的函数【英文标题】:Typescript/Angular - Call separate function after modal result return 【发布时间】:2017-03-18 19:16:29 【问题描述】:

当我通过关闭或取消 Angular/Typescript 中的模式返回我的承诺时,我在调用单独的函数时遇到问题。也许我正在尝试做一些不可能的事情,但是我看到的所有示例要么将返回的数据记录回控制台或变量,要么引发警报。像这样:

modalInstance.result.then(function (result) 
    console.log(result);
);

我要做的是在返回结果后调用 separate 函数,例如:

modalInstance.result.then(function (result) 
    console.log(result);
    this.EditWidget(result);
);

但这不起作用,我似乎无法弄清楚为什么。我已经尝试了所有方法,但我想我只是错过了关于这里的承诺如何运作的一些东西。

有什么想法吗?

【问题讨论】:

我没有看到您发布的代码有任何问题。是什么让您认为存在错误?该功能是否在承诺之外起作用?你能提供更多的代码来展示你在做什么吗? 【参考方案1】:

我的猜测是this 不是你所期望的那样。您需要捕获 this 的值并在回调中使用捕获的值:

var that = this;
modalInstance.result.then(function (result) 
    console.log(result);
    that.EditWidget(result);
);

或者将函数绑定到这个:

var callback = function (result) 
    console.log(result);
    this.EditWidget(result);
;

modalInstance.result.then(callback.bind(this));

【讨论】:

太棒了!非常感谢!

以上是关于Typescript/Angular - 模态结果返回后调用单独的函数的主要内容,如果未能解决你的问题,请参考以下文章

使用 Ionic + TypeScript + Angular 的混合应用程序

Typescript (Angular) - JSON 模型反序列化

何时在 TypeScript / Angular 中使用接口和模型

Angular 2\TypeScript 中 export 关键字的确切含义是啥?

解读移动端的跨平台开发:TypeScript + Angular

循环内的承诺:TypeScript + Angular + IndexedDB