javascript - AngularJS 1.x 如何使用资源获取结果数组?

标签 javascript angularjs rest angularjs-service angular-resource

这是我在 factory.js 中写的:

app.factory('CustomerCompany', function($resource){
    return $resource('/customer_companies/:id.json', {id: "@_id"}, {
        'query':{method: 'GET', isArray:false},
        'getByCustomerAccount':{
            method: 'GET', 
            params: {customer_account_id: customer_account_id}, 
            isArray:true, 
            url:'/customer_companies/get_by_account/:customer_account_id.json'
        }
    });
});

因为我想获取属于特定 customer_account 的 customer_companies 列表,所以我需要提供 customer_account_id。

在我的 controllers.js 中,

app.controller('customerAccountEditController', function($scope, CustomerCompany) {
    $scope.data = {};
    var path        = $location.path();
    var pathSplit   = path.split('/');
    $scope.id       = pathSplit[pathSplit.length-1];
    var customer_account_id = $scope.id;

    $scope.list_of_companies = [];

    CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
        console.log(data);
        //$scope.list_of_delegates.push(data);
    }); 
});

我得到一个未定义的 customer_account_id。

我哪里出错了?

最佳答案

我认为您不需要在 $resource 中定义 params & 然后 URL 将变为 url:'/customer_companies/get_by_account/customer_account_id.json ' & 在调用方法时,您需要从 {customer_account_id: customer_account_id} 传递 customer_account_id,这样它会创建一个带有 customer_account_id= 的 URL 2 像这样。

服务

'getByCustomerAccount':{
      method: 'GET', 
      //params: {customer_account_id: customer_account_id}, //removed it
      isArray:true, 
      url:'/customer_companies/get_by_account/:customer_account_id'
}

Controller

CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id + '.json'}, function(data){
    console.log(data);
    //$scope.list_of_delegates.push(data);
}); 

关于javascript - AngularJS 1.x 如何使用资源获取结果数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196200/

相关文章:

javascript - 使用 laravel elixir 转译使用 "import"语句的 es6

javascript - 如何使用 select 和对象数组在 AngularJS 中设置模型的值

java - 泽西客户端 IPv6

arrays - 从结果集中检索列表数据并转换为 JSON

javascript - .toFixed 函数不适用于 js-object

javascript - 如何在 JavaScript 中传递查询参数和重定向

javascript - 需要根据 Angular js应用程序中的索引重新排序对象列表

java - 如何设置并显示本地数据库中的另一个字段?

ajax - 如何为 REST 后端/Ajax 前端应用程序设计认证和授权系统

javascript - 数组解构 - 意外行为