How can I extract a list of data using resource in AngularJS 1.x?

In my factories.js file, I have the following code:

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

The purpose of this code is to fetch a list of customer companies that belong to a specific customer account by supplying a customer_account_id.

When I look at my controllers.js file,

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 encountered an error stating "customer_account_id not defined."

Where could I have made a mistake in my implementation?

Answer №1

It is unnecessary to define params within the $resource in order for the URL to be structured as

url:'/customer_companies/get_by_account/customer_account_id.json'
. When calling a method, simply pass the customer_account_id as shown in
{customer_account_id: customer_account_id}
. This will generate an URL with customer_account_id=2.

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

Answer №2

Success story!

controllers.js

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

services.js

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

Modifications I made:

  1. I opted for
    /accounts/:customer_account_id/companies
    on the backend to display results.
  2. Recognizing that returned data is always an object, I set isArray in $resource to false.
  3. Following Pankaj Parkar's suggestion, I pass parameters in the controller when invoking fetchDataByAccount.

Answer №3

variables: {user_id: user_id},

The user_id you are attempting to assign is currently undefined.

Please update it as follows:

variables: {user_id: '@user_id'},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Converting Roman Numerals into Decimal Numbers using JavaScript Algorithm

I am eager to develop a Javascript Algorithm that can convert Roman numerals to Arabic using the provided methods below. Array.prototype.splice() Array.prototype.indexOf() Array.prototype.join() I have managed to find an algorithm that accomplishes this ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...

Eliminate specific elements from an array while retaining others

Here is a simple page setup: https://i.sstatic.net/z9MF9.png The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "S ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

Is there a way to integrate jQuery and Javascript into a Firefox add-on?

Having trouble creating a new element on the page? After checking both the page and domain during onload, it seems that everything is in order. But how can you successfully create a new element in the correct window page? window.addEventListener("load", f ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

Tips for clearing Nightwatch session storage efficiently

To ensure the pop-up functionality was working properly, I had to reset the browser's session storage. By doing this, the pop-up will reappear. Is there a way to clear the page's Session Storage in Nightwatch? ...

Exploring the interaction between nested view controllers and ng-click in AngularJS

There are 8 different jade views, but only one is loaded and filled with jquery into a div that has a controller. I have two questions: Do I need to define the controller again on top of my partial view (the same controller as the main one)? All views h ...

Occasionally, AJAX requests may not always be in the correct sequence

I'm struggling with the POST and GET requests. Everything seems to be in order on my server side until I send the data, but then things get jumbled up on the client side. For instance, the data should be received in reverse order as shown below: Data ...

Is it necessary to append the path with __dirname when utilizing Node's fs.readFile()?

Illustration: fs.readFile(path.join(__dirname, 'path/to/file'), callback); compared to fs.readFile('path/to/file', callback); Both methods appear to function properly, prompting me to inquire whether I can omit the __dirname prefix, ...

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

Preventing default behaviors in VueJS textarea components

I'm attempting to incorporate a slack-like feature that sends a message only when the exact Enter key is pressed (without holding down the Shift key). Looking at this Vue template <textarea type="text" v-model="message" @keyup.enter.exact="sendMe ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

Creating websites with Single-page applications by assembling HTML and JS fragments at build-time

As I prepare to tackle a large single-page app project, my main focus is on finding a more efficient way to develop it other than cramming everything into one massive file. My priority is ensuring the maintainability and testability of the app, which is wh ...

What methods are available to create distinctive, shareable links akin to those utilized by Zoom and Google Hangouts?

I'm currently developing a group video chat app and I'm facing the challenge of generating distinct shareable links for every chat room created. Can anyone guide me on how to accomplish this? My aim is for users to easily join the chat room when ...

Error Occurs When Executing minall Task with Grunt Package (ubuntu and windows)

I've been following a tutorial on installing AngularJS from https://docs.angularjs.org/misc/contribute but I'm facing an issue at this particular step: # Build AngularJS: grunt package Upon executing "sudo grunt package" command, the output ind ...

Are elements such as String and Number to be classified as "constructor functions" within JavaScript programming?

After spending a few weeks poring over tutorials, I've finally uncovered an interesting fact. When using the prototype property on a constructor function, the key/value pairs on that prototype property are actually copied to the proto property of the ...

Looking to tilt text at an angle inside a box? CSS can help achieve that effect!

Hey there, is it possible to achieve this with CSS or JavaScript? I require it for a Birt report. ...