Tips on dynamically passing parameters in Angular's $resource

Is there a way to dynamically pass a default parameter value in $resource? Take a look at the Plunker for reference. In the code snippet below, I've set the default parameter in the 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'm looking to make the default param timeStamp dynamic. Currently, when I click on the Refresh Button, the param value remains the same (Check in console)

This functionality is needed because IE caches data for the GET method and I want to avoid cached data

Answer №1

Here is a helpful guide for you.

app.service('myService', ["$http", function($http) {
    return $http.get('http://example.com/data', {
        params: {
            timestamp : Date.now() // <-- new timestamp will be generated and assigned to timestamp
        }
    });
}]);

Every time you call the myService method, it will include a query parameter timestamp with the current timestamp value in the URL.

Answer №2

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

The execution of code within a function only occurs when the function is called. On the other hand, all code inside an object declaration is executed as the object is being created. Consider this alternative approach.

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

Answer №3

According to Lekhnath, the accurate answer 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
        }
    })
}]);

Alternatively, if there is a need to provide default parameters:

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

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

Ways to update a single column in an HTML table when there is a change

I'm stuck trying to find a more efficient method for updating a column in an html table without having to reload the entire table. The table consists of player stats, all pulled from my MYSQL database and displayed in the table except for the last col ...

The most effective method for adding data to a <pre /> element is through VueJS

I have an electron app that executes a program and stores the output when data is received. My goal is to showcase the content of this output within an html pre element. One approach I can take is to create a variable and continuously add the output data ...

React Native's state changes dynamically, however, the JSX conditional rendering fails to update the user interface accordingly

Greetings and thank you in advance for your time! I'm currently facing a unique challenge with React where I am struggling to render a specific UI element based on a check function. My goal is to create a multiple selection filter menu, where clickin ...

Is there a way to turn off the "swipe to navigate back" feature in Microsoft Edge using JavaScript or jQuery?

Working on a website that features horizontal object rotation. For instance, starting with the front view of an object followed by side, back, other side, and then back to the front. In this case, there are 24 images of an object, each taken at a 15 degre ...

The functionality of Jquery autocomplete _renderItem appears to be malfunctioning

There seems to be an issue with the _renderItem function as it is not executing at all. I even tried using console.log to debug but no messages are being printed. I also attempted using various attributes like 'autocomplete', 'ui-autocomplet ...

Tips for invoking a reduce mechanism within a separate function

I need assistance with implementing a reduce function: users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0); within the following function structure: function calculateUserAverageAge(users) {}; To analyze this array of objects and calculate ...

Exploring D3 to extract nested information and build an interactive navigation tree

Recently, I've been working with d3's zoom circle feature from here: The data I'm dealing with is structured as a json array with various levels of arrays and objects. object = { class: "show", name: "Game of Thrones", childre ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

Issue with Magento site: Clicking on thumbnail photo does not update the large photo on mobile devices

As I navigate through a Magento site, I encounter a problem with the thumbnail images not reloading the larger image when clicked. Instead, the browser jumps to the top of the page and a hash symbol gets added to the URL. Based on this behavior, I suspect ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Difficulties encountered when trying to load liquid using Javascript

Having trouble loading the Shopify liquid object {{product.price | json}} into JS, as it's displaying NaN with the current code on the front end. Any suggestions on how to properly pass liquid into JS? I've tried two functions but neither seem t ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

While attempting to troubleshoot a program with mocha using the --debug-brk flag, it turns out that the debugging process actually

After setting up an open source project, I found that the mocha tests are running successfully. However, I am facing a challenge when trying to debug the functions being called by these tests. Every time I attempt to debug using 'mocha --debug-brk&apo ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

Utilizing Google Analytics within an Angular Single Page Application

After implementing Google Analytics (GA) in my Angular single page application and placing the tracking code at the bottom of the main index.html, I encountered an issue regarding incorrect pageview results. <script> (function(i,s,o,g,r,a,m){i["Go ...

Connect the parent object's `this` to the child object's `this` in JavaScript

Exploring the world of object-oriented programming in JavaScript for the first time. It may sound like a simple question, but I really want to grasp this concept fully. var objA = { a : 10, b : 20, newobjB : { c : 100, funOfObjB: function(){ co ...

Eliminating the muted attribute does not result in the sound being restored

I am looking to implement a feature where a video loads automatically without sound, but when a user clicks a button labeled "Watch with Sound", the video restarts from the beginning and plays with sound. Below is the JavaScript code: let videoButton = do ...

The actions performed within an event listener function are undone once they have been carried out

I'm a newcomer to Javascript and I am currently experimenting with it. While browsing through a tutorial on w3schools, I came across an example of changing the color of a button after clicking on it. My idea was to take it a step further by loading a ...