2016-02-04 56 views
0

使用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> 
 

的dashboardSearch服務正確地返回與數據的對象。但我無法將數據分配給我的本地變量。

這裏是錯誤+數據來自谷歌瀏覽器CONSOLE.LOG

enter image description here

如何從我的服務的數據綁定到我的本地類變量?

+0

它與'this'關鍵字做。在SO上有一個以前的答案,它很好地寫了「這個」的工作原理以及如何總是引用正確的'this'實例。 http://stackoverflow.com/a/20279485/1260204 – Igor

回答

2

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); 
 
    }); 
 
};