[英]How to use data from API in factory AngularJS
我有以下代碼,該代碼使用人員數組中的數據來計算人員工資。
'use strict'; var app = angular.module('app', []); app.factory('staffFactory', function ($http) { var staff = [ {"id": "1","name": "Kate","rate": "10", "hours": "10"}, {"id": "2","name": "John","rate": "20", "hours": "10"}, {"id": "3","name": "Matt","rate": "15", "hours": "10"} ]; function calcPayInner(){ var unique = {}, distinct = [],pay = []; for (var i in staff) { if (typeof (unique[staff[i].id]) == "undefined") { distinct.push(staff[i].id); } unique[staff[i].id] = unique[staff[i].id] || {pay:0}; unique[staff[i].id].name = staff[i].name; unique[staff[i].id].pay += (parseInt(staff[i].rate, 10) * parseInt(staff[i].hours, 10)); } for (var p in unique) { pay.push([p, unique[p]]); pay.sort(function (a, b) { return (b[1].pay - a[1].pay); }); } return pay; } var staffService = {}; staffService.allStaff = function () { return staff; }; staffService.CalcPay = function () { return calcPayInner(); }; return staffService; }); app.controller('MainCtrl', ['$scope', 'staffFactory', function ($scope, staffFactory) { $scope.staff = staffFactory.allStaff(); console.log($scope.staff); $scope.CalcPay = staffFactory.CalcPay(); $scope.keyPress = function(keyCode){ $scope.CalcPay = staffFactory.CalcPay(); }; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="MainCtrl"> <table> <tr><td>name</td><td>rate</td><td>hours</td></tr> <tr ng-repeat="s in staff"> <td>{{s.name}}</td> <td><input ng-keyup="keyPress(s.rate)" ng-model="s.rate"></td> <td><input ng-keyup="keyPress(s.hours)" ng-model="s.hours"></td> </tr> </table> <table> <tr><td>name</td><td>pay</td></tr> <tr ng-repeat="b in CalcPay"> <td>{{b.1.name}}</td> <td>{{b.1.pay}}</td> </tr> </table> </div> </div>
所有這些都按預期工作,但是現在我想從API調用中獲取人員數據,而不是硬編碼數據。
我已經嘗試了以下。 ( 請參閱plnkr )
var staff = [];
var test = $http.get('staff.json')
.success(function(data) {
staff = data;
console.log(staff);
});
正如我在控制台中看到的那樣,這似乎返回了數據,但是我無法通過現有功能使它正常工作(返回空白數組)。
我也嘗試過將函數包裝在.success之后的.finally中,但是隨后我的函數變得不確定。
我如何在工廠的函數中使用API數據,這樣我的頁面才能像最初使用硬編碼數組那樣工作?
正如其他人提到的那樣,問題是您試圖在數據可用之前獲取數據。 解決此問題的方法是,如果您想保持數據的單一來源,則在工廠內部使用諾言。
下面的代碼使用q
因此您必須將其注入工廠。
app.factory('staffFactory', function ($http, $q) {}
allStaff實施
/* Private var to hold the staff */
var staff = [];
// this method returns a promise
staffService.allStaff = function () {
var deferred = $q.defer();
// check if staff is already fetched from server if yes resolve the promise immediately
if (staff.length > 0) {
// we have data already. we can avoid going to server
deferred.resolve(staff); // staff holds all the data
} else {
// data is not available yet. fetch it from server
$http.get('staff.json')
.success(function(data) {
// once data is available resolve
staff = data;
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
}
return deferred.promise;
};
在控制器中。
staffFactory.allStaff().then(function (staff) {
$scope.staff = staff;
console.log($scope.staff);
$scope.CalcPay = staffFactory.CalcPay();
$scope.keyPress = function(keyCode) {
$scope.CalcPay = staffFactory.CalcPay();
};
});
檢出plunkr
這是我的方法:
$scope.documents = [];
$http.post('get_xml.php')
.then(function (result) {
$scope.documents = result.data;
console.log(result.data);
});
據我所知.then
是一個異步函數,它將在數組可用時立即對其進行更新。
因此,在您的情況下,應為:
app.factory('staffFactory', function ($http) {
var staff = [];
var test = $http.get('staff.json').then(function(result) {
staff = result.data;
console.log(staff);
});
/* Rest of your code... */
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.