打字稿:从异步函数

时间:2016-02-04 13:10:09

标签: javascript asynchronous typescript

使用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>
 
&#13;
&#13;
&#13;

dashboardSearch服务正确返回包含数据的对象。但是我无法将数据分配给我的本地变量。

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

enter image description here

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

1 个答案:

答案 0 :(得分:3)

&#13;
&#13;
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);
  });
};
&#13;
&#13;
&#13;