简体   繁体   中英

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

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

To answer my own question, it was actually quite simple... Simply appending the query parameters to the resource path worked. When calling Receipt.query({freightBill: 123}) , Angular intelligently appends &freightBill=123 to the end of the path. Without the page, size and sort parameters there, Angular just appends ?freightBill=123 since it's the only parameter.

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?page=' + page + '&size=' + size + '&sort=' + sort);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM