[英]how to use angular and JavaScript promises to return some data?
我試圖從本地存儲中獲取一些數據,但我想在ready
使用日期。 就像是:
// this belongs to a Helper factory
getData: function(){
var deferred = jQuery.Deferred();
setTimeout(function(){
var data = {
description: localStorageService.get('description'),
};
deferred.resolve()
}, 10);
return deferred.promise();
},
// I set it up so that in the controller I can do
// $scope.data = Helper.getData();
與我的示例類似,我只想在從localstorage獲取description
返回data
對象
我正在使用angularjs,所以我希望在解決了承諾后在我的視圖中顯示{{data}}
。 比如可能使用ng-hide
或類似的東西。
無論如何,我的問題是關於建立這個承諾。
有任何想法嗎?
$ timeout()返回一個promise,所以這有效:
getData: function(){
return $timeout(function(){
return localStorageService.get('description'),
},3000);
}
用法:
getData().then(function(data){
console.log(data);
})
好吧, $q
是通常用於處理angularjs中的promise的庫,因為你是從本地存儲中讀取的,這是一個同步操作我不知道你為什么要返回一個promise,這通常是以角度來完成的。是這樣的:
getData: function(){
var deferred = $q.defer();
$timeout(function(){
var data=localStorageService.get('description'),
deferred.resolve(data);
},3000);
return deferred.promise;
}
用法:
getData().then(function(data){
console.log(data);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.