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

时间:2015-10-18 09:12:20

标签: javascript angularjs rest angularjs-service angular-resource

这是我在我的工厂中写的.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未定义。

我哪里出错了?

3 个答案:

答案 0 :(得分:1)

我认为您不需要在Application.Run(Form1()); &内部定义params。然后网址将变为$resource&在调用方法时,您需要从url:'/customer_companies/get_by_account/customer_account_id.json'传递customer_account_id,以便创建一个{customer_account_id: customer_account_id}像这样的somtehing的网址。

<强>服务

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'
}

答案 1 :(得分:1)

这对我有用。

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. 我意识到返回的数据始终是对象形式,因此我将isArray中的$resource更改为false
  3. 当我打电话给getByCustomerAccount
  4. 时,我按照Pankaj Parkar在控制器中建议的方式传递参数

答案 2 :(得分:0)

params: {customer_account_id: customer_account_id},

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

尝试params: {customer_account_id: '@customer_account_id'},