Search code examples
javascriptangularjsngresource

Is it possible to set default query parameters on an resource in AngularJS?


If I have a simple resource defined like the following, it's my understanding that I can call the Receipt.query() method to get a collection back from the server. It's also my understanding that if I call Receipt.query({freightBill: 123}), then freightBill gets added as a query parameter like /distribution/inbound?freightBill=123. How could I pass query parameters in this fashion, but then from my factory, also add default query parameters for page, size and sort?

The resulting request might look like /distribution/inbound?freightBill=123&page=0&size=20&sort=number,desc

angular.module('webappApp')
  .factory('receipts', function ($http, $resource, $location) {
    var search = $location.search();
    var page = search.page||0;
    var size = search.size||20;
    var sort = search.sort||'number,desc';

    return $resource('/distribution/inbound');
  });

Solution

  • second parameter of the $resource is for default parameters. DOCS : Link

    angular.module('webappApp')
      .factory('receipts', function ($http, $resource, $location) {
        return $resource('/distribution/inbound',{page:0,size:20,sort:'number,desc'});
      });
    

    these make them 'defaults'. Meaning you can override by passing new values to .query like Receipt.query({freightBill: 123,size:20,page:2})