Search code examples
javascriptangularjsangular-resource

How to pass query parameter array using Angular $resource


I'm trying to enable a feature where users can be searched for based on multiple tags (an array of tags) using the following structure:

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

I have this working on my node server and have successfully tested it using Postman. The issue I'm running into is how to structure this GET request in my Angular service using $resource. I have found documentation for $http stating that adding params:{'tag[]': tag} to the request object will do the trick, but cannot find anything regarding $resource.


Solution

  • In angular you can pass array as query string using $resource

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

    In 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 request url like:

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

    you get %5B%5D instead of [] in your request url

    and if you expect return array instead of object then you should use

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