角 v.1.6.1
我正在尝试使用 $q.defer().promise 返回一个集合,但我只得到一条记录,而不是从我的服务返回的两条记录。
该模型:
angular.module('app').factory('User',
function() {
/**
* Constructor, with class name
*/
function User(id, firstName, lastName, startDate) {
// Public properties, assigned to the instance ('this')
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.startDate = startDate;
}
/**
* Public method, assigned to prototype
*/
User.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
User.apiResponseTransformer = function (responseData) {
if (angular.isArray(responseData)) {
return responseData
.map(User.build)
.filter(Boolean);
}
return User.build(responseData);
}
/**
* Static method, assigned to class
* Instance ('this') is not available in static context
*/
User.build = function(data) {
return new User(
data.Id,
data.FirstName,
data.LastName,
data.StartDate
);
};
/**
* Return the constructor function
*/
return User;
});
服务
(function () {
'use strict';
var serviceId = 'userService';
angular.module('app').factory(serviceId, ['common', '$http', 'config', 'User', userService]);
function userService(common, $http, config, User) {
var $q = common.$q;
var defer = $q.defer();
var service = {
getUsers: getUsers,
getUser: getUser
};
return service;
function getUser(id) {
$http({
method: 'get',
url: config.remoteServiceName + 'users/' + id
}).then(function (response) {
defer.resolve(User.apiResponseTransformer(response.data));
}).then(function (response) {
defer.reject(response);
});
return defer.promise;
}
function getUsers(startDate) {
$http({
method: 'get',
url: config.remoteServiceName +'users/',
params: {
startDate: startDate
}
}).then(function (response) {
var users = [];
angular.forEach(response.data, function (value, key) {
users.push(User.apiResponseTransformer(value));
});
defer.resolve(users);
}).then(function(response) {
defer.reject(response);
});
return defer.promise;
}
}
})();
视图方法
function getUser() {
userService.getUser(1).then(function successCallback(data) {
vm.user = data;
}).catch(function () {
log('An error occured trying to get user...');
});
}
function getUsers() {
userService.getUsers(new Date().toUTCString()).then(function successCallback(data) {
vm.users = data;
}).catch(function () {
log('An error occured trying to get user...');
});
}
在视图内部,getUser 调用功能与预期相同,但 getUsers 仅从服务接收集合中的第一项。我已经验证 response.data 确实包含整个对象集合,并且这些对象被推送到 users 数组中。
即使调用 defer.resolve(response.data) 也只会发送集合中的第一项。
任何帮助表示赞赏!