2016-04-22 28 views
5

我是新來的AngularJS,我需要訪問它的承諾內部分配的Javascript如何訪問內部承諾聲明的變量在AngularJS

this.reqData= this.profileService.getData(); 
var resp1 = angular.fromJson(this.reqData); 
this.data1; 

var that = this; 
resp1.$promise.then(function (data) { 
    that.data1= data.resource.resource; 
}).catch(function (error) { 
    console.log(error); 
}); 

console.log(this.data1); 

可變數據1從HTML訪問的變量,但它在Javascript中顯示undefined

+0

您不在諾言之外訪問它。你不能從未來獲取價值(除非你創造時間旅行)。 – Bergi

回答

6

承諾是異步的。問題是,當你到達console.log時,$promise.then代碼還沒有運行。 您必須等待承諾履行才能訪問該數據。

要應用到值的任何操作必須做是回調函數你傳遞給then

resp1.$promise.then(function (data) { 
    var data1 = data.resource.resource; 
    // do all your processing on data1 *here* 
    console.log(data1); 
}).catch(function (error) { 
    console.log(error); 
}); 

AngularJS能夠當它得到了更新您的HTML數據,因爲$promise是Angular-aware - 它知道,一旦你的回調已經運行,它必須告訴AngularJS刷新/重新繪製頁面(從而更新數據)。

1

因爲你不知道什麼時候promise回報,所以它不會立即爲您提供在console.log(this.data1);

您可以訪問callback內部數據。

resp1.$promise.then(function (data) { 
    that.data1= data.resource.resource; 
    }).catch(function (error) { 
    console.log(error); 
});