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

AngularJS 1.x How do I use resource to fetch an array of results?

这是我在 factories.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 未定义。

我哪里错了?

params: {customer_account_id: customer_account_id},

您尝试在此处分配的 customer_account_id 未定义。

尝试params: {customer_account_id: '@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},这样它将创建一个 URL 和 customer_account_id=2 类似的东西。

服务

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

控制器

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

这对我有用。

controllers.js

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

services.js

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

我改变了什么:

  1. 在服务器端,我决定使用/customer_accounts/:customer_account_id/customer_companies来呈现结果。
  2. 我意识到返回的数据总是对象形式,所以我将$resource中的isArray更改为false
  3. 我在调用 getByCustomerAccount
  4. 时按照 Pankaj Parkar 在控制器中建议的方式传递参数