我有一个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' });
})
;
在控制器中,我打电话:
$scope.employee = Employee.get({id: 'me'});
接下来,我想打电话:
$scope.departments = [];
angular.forEach($scope.employee.departmentIds, function (departmentId) {
$scope.departments.push(Department.get({ id: departmentId }));
});
但$scope.employee
是一个承诺对象,因此只有在第一个请求完成时才会知道$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 }));
});
});
问题是我需要在多个控制器中使用此信息,并且不希望在每个控制器中重复此代码。所以我的问题是:有没有办法将这两种资源结合起来,提供员工数据和该员工所属部门的数据?
答案 0 :(得分:2)
你可以这样做:
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;
}
}
}]);
你不需要改变控制器中的任何东西。
答案 1 :(得分:1)
这个答案基于@Beterraba的答案(但答案中的代码示例不正确):
服务:
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开始,您需要解开控制器上的任何承诺对象。我发现了这些信息here。