AngularJS无法通过$ routeParams创建$ resource的操作

时间:2018-09-30 05:40:25

标签: angularjs

employee.service.js

angular.
  module('core.employee').
  factory('Employee', ['$resource',
    function($resource) {
      return $resource('http://127.0.0.1:8007/api/business/:businessId/employees/:employeeId', {}, {
        query: {
          method: 'GET',
          params: {businessId: '', employeeId: ''},
          isArray: true
        },
        create: {
          method: 'POST',
          params: {businessId: '', employeeId:''}
        },
      });
    }
  ]);

在我的控制器内部:

    self.employees = Employee.query({businessId: $routeParams.businessId}, function(employees) {

    });
    self.create = function(){
      Employee.create({
        businessId: $routeParams.businessId,
        email: self.email,
        access: self.access.value
      }).$promise.then(function(employee) {
        self.errorMsg = "";
        self.employee = employee;
      }, function(errResponse) {
        console.log($routeParams.businessId);
        self.errorMsg = errResponse["data"];
      });
    }

currentUrl:http://127.0.0.1:8007/businesses/1/employees/create

我能够query名员工。但无法create。引发的错误是:

  

angular.js:13018 POST http://127.0.0.1:8007/api/business//employees/ 404(未找到)

发布数据的实​​际网址应为:http://127.0.0.1:8007/api/business/1/employees/

此处businessId似乎尚未传递到资源。但是在处理错误消息的函数内部:console.log($routeParams.businessId)给出1

config内的路线:

when('/businesses/:businessId/employees/create', {
      template: '<employee-create></employee-create>'
    }).

1 个答案:

答案 0 :(得分:1)

您没有正确连接$resource来将请求参数映射到请求路径。

$resource(
  'http://127.0.0.1:8007/api/business/:businessId/employees/:employeeId',
  // Set up default parameters to extract values from the corresponding
  // properties when the resource is used
  { businessId: '@businessId', employeeId: '@employeeId' },
  {
    query: {
      method: 'GET',
      isArray: true
    },
    create: {
      method: 'POST',
    },
  });

未能映射参数会导致结果请求路径中缺少片段。

The documentation for the default parameters arguments mentions this mapping behaviour:

  

如果参数值以@为前缀,则将从数据对象上相应的属性中提取该参数的值(在使用请求主体调用操作时提供)。