我有一个 RESTful API,可以为我提供员工和部门信息。在我的 AngularJS 应用程序中,我需要了解员工以及员工所属的部门。我为此定义了两个工厂服务:
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' });
})
;
在 Controller 中,我调用:
$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
只有在第一个请求完成时才会知道。
我可以这样解决:
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 }));
});
});
问题是我需要在多个 Controller 中使用此信息,并且不想在每个 Controller 中重复此代码。所以我的问题是:有没有办法将这两种资源结合起来作为一个服务,既提供员工数据又提供该员工所属部门的数据?
最佳答案
你可以这样做:
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) {
var data = SimpleEmployee.get({id: params.id}, function (employee) {
var obj = {
employee: employee,
departments: []
};
angular.forEach(employee.departmentIds, function (departmentId) {
obj.departments.push(Department.get({ id: departmentId }));
});
return obj;
});
return data;
}
}
}]);
并且您不需要更改 Controller 中的任何内容。
关于angularjs - 在 AngularJS 中组合资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289820/