Guide to using Angular $resource to pass query parameter array

My goal is to implement a feature that allows users to be searched based on multiple tags (an array of tags) using the specified structure:

GET '/tags/users?tag[]=test&tag[]=sample'

I have managed to make this work on my node server and have successfully tested it with Postman. The challenge I am facing now is figuring out how to format this GET request within my Angular service using $resource. While there are resources available for $http suggesting that adding params:{'tag[]': tag} to the request object should work, I have not been able to find similar information for $resource.

Answer №1

If you're working with Angular, it's possible to pass an array as a query string using the $resource functionality.

Within the controller:

angular.module('myApp').controller('userController',['$scope','userService', '$location',
    function($scope, userService, $location){
        $scope.searchQuery = {};

        $scope.SearchUsers = function() {
            $scope.roles = ['admin', 'register', 'authenticate'];
            $scope.searchQuery.name ='xxx';
            $scope.searchQuery['roles[]'] = $scope.roles;
            userService.searchUsers($scope.searchQuery)
                .$promise.then(function (response) {
                    $scope.users = response.users;
                });
        };
   }
]);

Within the service:

angular.module('myApp').factory('userService', ['$resource',
function($resource) {

return {
    searchUsers: function(searchQuery){
        var searchRequest = $resource('/auth/search/user', {}, {
            'get': {method: 'GET'}
        });
        return searchRequest.get(searchQuery);
    }
};
}
]);

The URL of the request will look like this:

/auth/search/users?name=xxx&roles%5B%5D=admin&roles%5B%5D=register&roles%5B%5D=authenticate

You may notice that instead of [], you see %5B%5D in your request URL.

If you need the return value to be an array rather than an object, make sure to use:

'get': {method: 'GET', isArray: true}

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

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

How to Fetch a Singular Value from a Service in Angular 4 Using a Defined Pattern

I am currently working on developing a service in Angular 4 (supported by a C# RESTful API) that will facilitate the storage and retrieval of web-application wide settings. Essentially, it's like a system for key-value pair lookups for all common appl ...

Presenting JSON output using AngularJS

I'm struggling to showcase JSON response data using AngularJS Despite able to see the results in DevTools, I am facing issues while displaying them on the screen. Here is the controller code: MovieApp.controller('movieAdminCtrl', ['$ ...

Guide on making a submit and close button within an overlay

Seeking a button to both submit and close an overlay window. The button code is as follows: <a href="javascript:additem('Info to add here', 10.00,1);" role="button"><button class="purchase btn btn-warning">Select</button></ ...

Issue with ng-bind-html not properly rendering content within audio tag

Currently, I am working with a variable called result.questionText. It currently holds the question: "<i>How many times are the hands of a clock </i>at right angle in a day?<audio controls ng-src="media/abc.mp3"></audio>". Instead o ...

connecting elements in an object's array to another array within a nested object

Is there a way to iterate through each string value in the imageKeys array and use it to create a URL for each object in the images array within the nested ImageList object, all without changing the original object? const myInitialStateFromParent = { ...

Odd gap beside Bootstrap5 navbar that needs fixing

While working on a layout featuring a left-sided nav-bar menu, I encountered an odd blank space between the navbar and the main content area. Can anyone shed light on why this space appears and how to eliminate it? For reference, here is the code snippet: ...

Mastering Meteor: Techniques for Manipulating Mongodb Data in Real Time Display

Within my Meteor application, I have accomplished the successful publication of data from the server and its subscription on the client side. Instead of directly displaying raw data on the client's screen, I am interested in performing some calculatio ...

Display data in the center of a doughnut chart using angular-chart.js

I have decided to utilize the angular-chart.js library () to create a doughnut chart. One of my requirements is to display the total data in the center of the chart, similar to what is shown below: View this image Is it possible to achieve this using the ...

Activating a inaccessible element

Attempting to enable a disabled element upon clicking a P element, the following code snippet demonstrates storing a value from one textbox into another. The appended div contains a subsequent textbox which will be disabled. On mouseover of the div, option ...

Tips for displaying a close icon after completing a file upload

I need to implement a feature where once a user uploads a file, a cross sign should be enabled on the file. I attempted to use javascript for this functionality, but it seems to not be working as expected. There are more than 8-10 different file types that ...

Ways to conceal an animated gif once it has been downloaded?

Is it possible to have an animated gif image vanish once server-side Java code runs and the client receives an HTTP Response from the webserver without relying on Ajax? I am currently utilizing the following Struts2 submit button: <s:submit value="sho ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

Encountering an issue with connecting nodejs to mqlight

I have been working with nodejs and mqlight to test out some sample code provided on https://www.npmjs.com/package/mqlight. My current setup consists of nodejs 5.5.0 and npm version 3.3.12. To install mqlight, I used the command npm install mqlight. ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

The Antd table documentation mentions that rowKey is expected to be unique, even though it appears they are already

Having trouble with a React code issue. I have a list of products, each with an array of 7 items that contain 40 different data points. This data is used as the source for a table. {label : someStringLabel, key: someUniqueKey, attribute1: someInt,..., at ...

Verify if the program is operating on a server or locally

My current project involves a website with a game client and a server that communicate via sockets. The issue I'm facing is how to set the socket url depending on whether the code is running on the server or my local PC. During testing and debugging, ...

Deciphering JSON data within AngularJS

When I retrieve JSON data in my controller using $http.get, it looks like this: $http.get('http://webapp-app4car.rhcloud.com/product/feed.json').success(function(data) The retrieved data is in JSON format and I need to access the value correspo ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...