【问题标题】:Typescript: Assign value to variable from Async function打字稿:从异步函数为变量赋值
【发布时间】:2016-05-14 02:46:51
【问题描述】:

我是否正在尝试使用 Typescript 将异步服务调用的返回值分配给局部变量;

private searchResult;

public search():void{
             this.DashboardService.dashboardSearch(this.searchParams)
                .then(
                    function (result:ISearchResult) {
                        // promise was fullfilled
                        console.log(result);
                        this.searchResult = result;
                    },
                    function (error) {
                        // handle errors here
                        console.log(error);
                    }
                );
        };
<div id="dashboard-content" ng-controller="dashboardCtrl as vm">
    <h3>{{vm.searchResult}}</h3>
</div>
 

dashboardSearch 服务正确返回带有数据的对象。但我无法将数据分配给我的局部变量。

这是来自 Google Chrome console.log 的错误 + 数据

如何将服务中的数据绑定到本地类变量?

【问题讨论】:

  • 它与this 关键字有关。之前有一个关于 SO 的答案很好地说明了 this 如何工作以及如何始终引用正确的 this 实例。 stackoverflow.com/a/20279485/1260204

标签: javascript asynchronous typescript


【解决方案1】:

private searchResult;

public search():void {
  let that = this;
  
  this.DashboardService.dashboardSearch(this.searchParams)
  .then(function(result:ISearchResult) {
    // promise was fullfilled
    console.log(result);
    that.searchResult = result;
  }, function (error) {
    // handle errors here
    console.log(error);
  });
};

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 2019-01-08
    • 2023-02-14
    • 2021-04-10
    • 2016-11-02
    • 2018-05-03
    • 2017-12-01
    • 2019-10-16
    • 2021-01-05
    相关资源
    最近更新 更多