简体   繁体   中英

How do I pass parameters to an Angular service?

I have an Angular service:

angular.module('transactionService', ['ngResource']).
    factory('Transaction', function($resource){ 
      return $resource('/api/transaction/:transactionId', {}, {
        'query':   {method:'GET',     params:{transactionId : ''},          isArray : true},
        'get':     {method:'GET',     params:{transactionId : '@_id.$oid'}, isArray : false},
        'save':    {method:'POST',    params:{transactionId : ''},          isArray : false},
        'update':  {method:'PUT',     params:{transactionId : '@_id.$oid'}, isArray : false},
      });
});

Which I call as:

transaction = {
   _id : { $oid : '20495823405984059' }
}
Transaction.update(transaction, function(d) {});

But it fetches the URL:

/api/transaction/@_id.$oid

instead of:

/api/transaction/20495823405984059

The documentation shows that this is the correct way to pass parameters, but they aren't getting interpolated. What am I doing wrong?

Try:

angular.module('transactionService', ['ngResource']).
    factory('Transaction', function($resource){ 
      return $resource('/api/transaction/:transactionId', {}, {
        'query':   {method:'GET',     params:{transactionId : ''},          isArray : true},
        'get':     {method:'GET',     params:{transactionId : '@transactionId'}, isArray : false},
        'save':    {method:'POST',    params:{transactionId : ''},          isArray : false},
        'update':  {method:'PUT',     params:{transactionId : '@transactionId'}, isArray : false},
      });
});

Call it like this:

transaction = {
   transactionId : '20495823405984059' //your problem is the key transactionId is missing
}
Transaction.update(transaction, function(d) {});

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