在 AngularJS 中组合资源 [英] Combining resources in AngularJS
问题描述
我有一个 RESTful API,可以为我提供员工和部门信息.在我的 AngularJS 应用程序中,我需要知道员工和员工所属的部门.我为此定义了两个工厂服务:
I have a RESTful API that provides me with employees and departments. In my AngularJS app, I need to know the employee and the departments the employee belongs to. I have defined two factory services for that:
angular.module('myApp.services', [])
.factory('Employee', function ($resource) {
return $resource ('/api/employees/:id', { id: '@id' });
})
.factory('Department', function ($resource) {
return $resource ('/api/departments/:id', { id: '@id' });
})
;
在控制器中,我调用:
$scope.employee = Employee.get({id: 'me'});
接下来,我想打电话:
$scope.departments = [];
angular.forEach($scope.employee.departmentIds, function (departmentId) {
$scope.departments.push(Department.get({ id: departmentId }));
});
但是 $scope.employee
是一个 promise 对象,所以 $scope.employee.departmentIds
只有在第一个请求完成时才会知道.
But $scope.employee
is a promise object, so $scope.employee.departmentIds
will only be known when the first request is completed.
我可以这样解决:
Employee.get({id: 'me'}).$promise.then(function (employee) {
$scope.employee = employee;
$scope.departments = [];
angular.forEach(employee.departmentIds, function (departmentId) {
$scope.departments.push(Department.get({ id: departmentId }));
});
});
问题是我在多个控制器中都需要这个信息,不想在每个控制器中都重复这个代码.所以我的问题是:有没有办法将这两种资源组合为一项服务,既提供员工数据又提供该员工所属部门的数据?
The problem is that I need this information in multiple controllers, and don't want to repeat this code in every controller. So my question is: is there a way to combine these two resources as a service which provides both the employee data and the data of the departments to which that employee belongs?
推荐答案
此答案基于@Beterraba 的答案(但该答案中的代码示例不正确):
This answer is based on the answer of @Beterraba (but the code example in that answer is incorrect):
服务:
angular.module('myApp.services', [])
.factory('SimpleEmployee', function ($resource) {
return $resource ('/api/employees/:id', { id: '@id' });
})
.factory('Department', function ($resource) {
return $resource ('/api/departments/:id', { id: '@id' });
})
.factory('Employee', ['SimpleEmployee', 'Department', function(SimpleEmployee, Department) {
return {
get: function(params) {
return SimpleEmployee.get({id: params.id}).$promise.then(function (employee) {
employee.departments = [];
angular.forEach(employee.departmentIds, function (departmentId) {
employee.departments.push(Department.get({ id: departmentId }));
});
delete employee.departmentIds;
return employee;
});
}
}
}]);
控制器:
Employee.get({ id: 'me' }).then(function (employee) {
$scope.employee = employee;
});
从 AngularJS 1.2 RC3 开始,您需要解开控制器上的所有 promise 对象.我在此处找到了此信息.
From AngularJS 1.2 RC3 on you need to unwrap any promise objects on the controller. I found this information here.
这篇关于在 AngularJS 中组合资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!