How to pass dynamic param in angular $resource

1.3k views Asked by At

I want to pass dynamic value of default param in $resource. Please look into the Plunker. Here when I had passed default param in factory as

app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', {timeStamp : (new Date()).getTime()}, {
        query : {
            method : 'GET',
            isArray : true,
            cache : false
        }
    })
}]);

I want default param timeStamp to be dynamic. currently when i click on Refresh Button the param value goes always same (Check in console)

I need this functionality because IE make cache on GET method and I don't want cache data

3

There are 3 answers

3
Lekhnath On BEST ANSWER

This should help you.

app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', {}, {
        query : {
            method : 'GET',
            isArray : true,
            params : { ts : Date.now } // <-- new timestamp will be genrated and assigned to ts
        }
    })
}]);

each time you invoke myFactory.query() method a querystring ts with current timestamp value will appear in url.

0
Amit Mourya On

The correct answer as said by Lekhnath is

app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', {}, {
        query : {
            method : 'GET',
            isArray : true,
            params : { ts : Date.now } // <-- new timestamp will be genrated and assigned to ts
        }
    })
}]);

or if we want to pass in default param section it can be done as

app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', { ts : Date.now }, { // <-- new timestamp will be genrated and assigned to ts
        query : {
            method : 'GET',
            isArray : true
        }
    })
}]);
1
Matt Rattray On
var app = angular.module('plunker', ['ngResource']);

app.controller('MainCtrl', function($scope,myFactory) {
  $scope.refresh = function(){
    myFactory.query({timeStamp : (new Date()).getTime()}).$promise.then(function(){})
  }
});
app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', {}, {
        query : {
            method : 'GET',
            isArray : true,
            cache : false
        }
    })
}]);

Code inside of a function is not executed until the function is called. However within a declaration of an object, all of it is executed as the object's being created. You may as well have of had this.

app.factory('myFactory', ["$resource", function($resource) {
    return $resource('http://google.com', {timestamp: 1433865286924}, {
        query : {
            method : 'GET',
            isArray : true,
            cache : false
        }
    })
}]);