我想在服务中获取一些异步数据,这些数据需要在那里进一步处理。代码在plnkr,
我模拟了一个超时的异步调用,一旦收到数据,UI就会更新。但是,我还需要处理服务中的数据 (doubleData) 并稍后在我的 UI 中使用。说,我需要用一些细节来扩充数据。
由于数据在{{doubleData()}}
被调用时为空,因此它永远不会填充它。如何在我的服务中实现进一步处理数据的方法(填充异步 - 比如说 $http)?
索引.html
<!doctype html>
<html ng-app="myApp">
<head>
<script type="text/javascript" src="../../../angular-1.0.2/angular.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
{{data}}<br>
{{doubleData()}}
</div>
</body>
</html>
脚本.js
var app = angular.module('myApp',[]);
app.factory('myService', function($timeout) {
var data = [],
doubleData = [];
var myService = {};
myService.async = function() {
$timeout(function(){
data.length = 0;
for(var i = 0; i < 10; i++){
data.push({val: Math.random()});
}
}, 5000);
};
myService.data = function() { return data; };
myService.doubleData = function() {
doubleData = []
for (var i = 0; i < data.length; i++) {
doubleData.push({val: 10* data[i]});
};
return doubleData;
};
return myService;
});
app.controller('MainCtrl', function( myService,$scope) {
myService.async();
$scope.data = myService.data();
$scope.doubleData = myService.doubleData;
});
输出(5秒后):
[{"val":0.4908415926620364},{"val":0.25592787051573396},{"val":0.8326190037187189},{"val":0.6478461190126836},{"val":0.8502937415614724},{"val":0.19280604855157435},{"val":0.06115643493831158},{"val":0.5100495833903551},{"val":0.4134843284264207},{"val":0.5548313041217625}]
[{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null}]