Combining resources in AngularJS

为君一笑 提交于 2019-12-03 09:02:17

You can do something like that:

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;
            }
        }
    }]);

And you dont need to change anything in your controller.

This answer is based on the answer of @Beterraba (but the code example in that answer is incorrect):

Service:

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;
                });
            }
        }
    }]);

Controller:

Employee.get({ id: 'me' }).then(function (employee) {
    $scope.employee = employee;
});

From AngularJS 1.2 RC3 on you need to unwrap any promise objects on the controller. I found this information here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!