angularjs中的异步数据检索
Async data retrievel in angularjs
我的angularjs应用程序中存在异步问题。
我想做的是从远程服务器(在prefsService.js中)检索数据。然后将数据值分配给控制器(在prefsController.js中)中的变量。
这是prefsService.js文件:
(function() {
'use strict';
angular
.module('app')
.factory('PrefsService', PrefsService);
PrefsService.$inject = ['$resource','PrefsResource'];
function PrefsService($resource,PrefsResource) {
var initialize = function() {
var twentyFourHourTime = null;
var decimalTime = null;
var startDayOfWeek = null;
var roundingOption = null;
var roundingIncrement = null;
PrefsResource.get({key:"TwentyFourHourTime"}, function(data) {
if (data.result.value === null||undefined) {
twentyFourHourTime = 0;
} else {
twentyFourHourTime = data.result.value;
}
PrefsResource.get({key:"DecimalTime"}, function(data) {
if (data.result.value === null||undefined) {
decimalTime = 0;
} else {
decimalTime = data.result.value;
}
PrefsResource.get({key:"startDayOfWeek"}, function(data) {
if (data.result.value === null||undefined) {
startDayOfWeek = 0;
} else {
startDayOfWeek = data.result.value;
}
return {"twentyFourHourTime":twentyFourHourTime,"decimalTime":decimalTime,"startDayOfWeek":startDayOfWeek}
});
});
});
};
return {
initialize: initialize
};
}
})();
这是prefsController.js文件:
vm.test=PrefsService.initialize();
console.log('Prefs data initialized', vm.test);
当我运行它时,vm.test总是"未定义"的。
我该怎么办?Thx!
我还没有对此进行语法检查,但与所有异步编程一样,它的要点是promise。这个问题是一个骗局(谁还能找到这类问题的主骗局?)
(function() {
'use strict';
angular
.module('app')
.factory('PrefsService', PrefsService);
PrefsService.$inject = ['$resource','PrefsResource'];
function PrefsService($resource,PrefsResource) {
var initialize = function() {
//return a promise
return $q
.all([
PrefsResource.get({key:"TwentyFourHourTime"}),
PrefsResource.get({key:"DecimalTime"}),
PrefsResource.get({key:"startDayOfWeek"})
])
.then(function(values) {
var
twentyFourHourTime = values[0],
decimalTime = values[1],
startDayOfWeek = values[2];
//return the value (object) when all promises have resolved
return {
"twentyFourHourTime":twentyFourHourTime.result.value || 0,
"decimalTime":decimalTime.result.value || 0,
"startDayOfWeek":startDayOfWeek.result.value || 0
}
})
}
return {
initialize: initialize
};
}
})();
PrefsService
.initialize()
//use the promise API to log messages only after the promise has resolved
.then(function(prefs) {
console.log('initialized');
console.log(prefs);
})
相关文章:
- 如何在corona sdk中从CK编辑器中检索数据
- 使用javascript进行JSON数据检索
- 使用JSON数据检索AJAX外部成功函数
- 将jquery HTML方法中的数据检索到数组中
- PHP/MySQL 时间数据检索和创建倒计时
- 将数据库数据检索到JSON-移动登录表单
- angularjs中的异步数据检索
- 如何将索引数据库表数据检索到变量
- 简单的Firebase数据检索
- 如何在 JQGard 加载时禁用数据检索
- 如何将角度数据检索到其他JS文件中
- 异步数据检索和缓存
- 如何从服务中将数据检索到指令(angularjs)中
- 动态表单字段和数据库数据检索
- PHP post请求数据检索使用Jquery AJAX
- javaScript中的异步数据检索
- Json数据检索jquery
- 在Firebase中使用Ionic异步数据检索的问题
- JQuery事件处理与数据检索通过POST
- Angular将特定数据检索到$scope变量中不起作用