Tips for passing parameters in a $resource request in angularJS

I have set up a factory like this:

angular.module('core.actor').factory('Actor', ['$resource',
    function ($resource) {
        return $resource('api/actor/:actorId/', {}, {
            query: {
                method: 'GET',
                isArray: true,
                cache: true
            },    
            update: {
                method: 'PUT'
            }
        });
    }
]);

In my paging function, I have the following conditional logic:

if (self.pk == "-6" && self.searchTerm == undefined) {
    self.actorsToAdd = Actor.query({
        offset: pageOffset,
        limit: pageLimit
    })
} else if (self.pk == "-6") {
    self.actorsToAdd = Actor.query({
        offset: pageOffset,
        limit: pageLimit,
        search: self.searchTerm
    })
} else if (self.searchTerm == undefined) {
    self.actorsToAdd = Actor.query({
        offset: pageOffset,
        limit: pageLimit,
        pk: self.pk.toString()
    })
} else {
    self.actorsToAdd = Actor.query({
        offset: pageOffset,
        limit: pageLimit,
        search: self.searchTerm,
        pk: self.pk.toString()
    })
}

This function modifies the GET request generated by the Actor object based on certain conditions. I am interested in parameterizing this function so that I can replace 'Actor' with a variable.

For example, something like this:

pageType = Movie;

var page = function (pageType){

  self.itemsToAdd = pageType.query({
      offset: pageOffset,
      limit: pageLimit
  })  
}

Is it feasible? If yes, how can it be achieved?

Answer №1

Instead of passing individual parameters into the query, I prefer to pass an object containing the query parameters.

angular.module('core.actor').factory('Actor', ['$resource',
  function ($resource) {
     return $resource('api/actor/:actorId/', {}, {
       query: {
       method: 'GET',
       isArray: true,
       cache: true,
       params: { queryParams: '@_queryParams' }
    },
    update: {
      method: 'PUT'
    }
  });
}
]);

Your call would then look something like this:

Actor.query({ queryParams: {
    offset: pageOffset,
    limit: pageLimit,
    pk: self.pk.toString()
}})

On the server side, I analyze the values in the parsed JSON params to construct the appropriate database query.

Does this align with what you were looking for after your latest comment?

angular.module('core.actor').factory('Api', ['$resource',
  function ($resource) {
    return {
      actor: $resource('api/actor/:actorId/', {}, {
        query: {
      method: 'GET',
      isArray: true,
      cache: true,
      params: {queryParams: '@_queryParams'}
    },
    update: {
      method: 'PUT'
    }
  }),
  movie: $resource('api/move/:moveId/', {}, {
    query: {
      method: 'GET',
          isArray: true,
          cache: true,
          params: {queryParams: '@_queryParams'}
        },
        update: {
          method: 'PUT'
        }
      })
    };
  }
]);

You can then use Api.movie.query() or Api.actor.query().

To give you a complete picture, here's how my server-side code looks when creating the query.

var constructUserQuery = function (queryParams) {
  var query = { $or: [], $and: [] };

  if (queryParams.name) {
    query.$and.push({ displayName: { $regex: queryParams.name,     $options: 'i'} });
  }

  if (queryParams.client) {
    query.$or.push({ client: mongoose.Types.ObjectId(queryParams.client) });
  }

  if (queryParams.roles) {
    query.$or.push({ roles: { $in: queryParams.roles }});
  }

  // Exclude current user if provided
  if (queryParams.user) {
    query.$and.push({ _id: { $ne: queryParams.user._id }});
  }

  // Remove empty arrays
  if (query.$or.length === 0) {
    delete query.$or;
  }

  if (query.$and.length === 0) {
    delete query.$and;
  }

  return query;
};

This implementation is tailored to my scenario but illustrates the concept. Conditional statements are only used in this section.

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

Customize your jQuery 3.x version by adding Ajax functionality tailored to your

I've been working on creating a custom jQuery 3.x version, but I'm facing the issue of maintaining the functionality of $.ajax even when ajax is not explicitly removed. Below are my build and grunt settings: grunt custom:-css/showHide,-deprecate ...

How to achieve a one-time use of JQuery scrollTo for scrolling to a specific

Currently, I am in the process of developing a website where I showcase my child pages using a slideshow on the main parent page. Each child page has a scroll down link that should smoothly transition to the first title above the image when clicked. Howeve ...

Avoiding errors during radio value changes when loading a component in Angular

I need assistance with setting a date using radio buttons. I encountered an error when I tried to change the value while the component was loading. html.component.html ... <div> <input type="radio" name="period" [checked]= ...

What is the best method for storing pug-formatted data in a database?

I am currently developing a JavaScript application where I utilize pug for templates and diskdb for storing data. Within my content, I have implemented pug syntax which may appear in the following format: p some content here p some more content here p: # ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

Issues with clicking in JS eventListener

I'm in need of some assistance with a small header issue in my project. I've included all the necessary header files so that you can run it in a snippet and see what's going on. The problem lies within my JS file. When running the file, you ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Execute the cucumber cli programmatically in the index.js file of a node application

Recently, I received an automation framework built in CucumberJS and Node with Selenium. However, the framework is using an outdated version of Cucumber that relies on promises. Wanting to take advantage of the latest synchronous step feature, I decided to ...

Having trouble with installing sass via Gem in the Windows terminal

I am working on creating a Web Application with Angular JS and I am currently in the process of developing an Admin Panel. For this project, I will be using the Flatlogic Angular Material Dashboard template from here. To set up the admin panel, I am follow ...

Activate lightbox on click to swap image source temporarily

I have implemented the Materialize CSS "Material Box" lightbox plugin, but I am facing an issue. I want all the thumbnails to be uniform in size, and when clicked, the full photo should be displayed. Currently, I am using the onclick function to change th ...

To verify if a user-entered numerical value matches the previously saved value and display an error message if it does not

important: The total is a numerical value that updates dynamically based on user input. <md-input-container class="md-block"> <input required type="number" ng-pattern="/^total$/" step="any" name="num" ng-model="house.No" style="max-width:1 ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Dealing with intricate query parameters in Express.Js

Currently, I am working on developing REST APIs using Express.js. One particular express route that I have set up is as follows: /api/customer I have incorporated multiple query parameters into this route, such as: /api/customer?name=jake /api/customer?c ...

The most basic Angular module configuration

What is needed to prevent the "no module: tut" error from occurring? <!DOCTYPE html> <html ng-app="tut"> <head> <script type="text/javascript" src="./jquery.js"></script> <script type="text/javascript" ...

Confirmation of Angular Password Verification

I am having an issue with the password matching functionality on my website. When a user types their password and then re-enters it in the confirm password field, they immediately receive a message saying the passwords do not match. I would like to displ ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

The error occurred at line 12 in the app.js file, where it is unable to access properties of an undefined object, specifically the 'className' property. This occurred within an anonymous function in an HTMLDivElement

I am facing an issue with my website where I have buttons on the right side. I want to use JavaScript to change the style of the button when it is clicked. When the page loads, the home button should have a background-color: green. However, when another bu ...

Verify your identity using Google reCaptcha during Passport authentication

I am currently working on integrating google reCaptcha into my signup form's back-end, which already includes passport authentication. The code I have so far looks like this: app.get('/signup', function(req, res) { // render the ...

AngularUI is encountering an issue with Google Maps where the map object is undefined

My attempt to utilize the GoogleMaps directive looks like this: Controller Methods $scope.myMarkers = []; $scope.mapOptions = { center : new google.maps.LatLng(35.784, -78.670), zoom : 15, mapTypeId : google.maps.MapTypeId.ROADMAP }; $scope ...

Issue encountered: Error in Node.js watchFile - "Undefined is not a function"

Just delving into the world of Node.js and experimenting with some basic code. I currently have the Node.js windows binary version 0.5.8 installed. Below is a snippet of my JavaScript code: var fs = require("fs"); fs.readFile('message.text ...