Search code examples
javascriptangularjsrestangularjs-serviceangular-resource

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


This is what I wrote in my 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'
        }
    });
});

Because I want to fetch a list of customer_companies that belong to a particular customer_account so I need to supply a customer_account_id.

In my 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);
    }); 
});

I get a customer_account_id not defined.

Where did I go wrong?


Solution

  • I think you don't need to define params inside your $resource & then URL will becomes url:'/customer_companies/get_by_account/customer_account_id.json' & while calling a method you need to pass the customer_account_id, from {customer_account_id: customer_account_id} so that it would create an URL with customer_account_id=2 somtehing like that.

    Service

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