Stop AngularJS $http promise from fetching cached JSON data

During the signup process of my AngularJS application, I continuously update a user object.

Instead of creating separate controllers for each signup step, I have opted to use one controller for all steps as the logic is quite similar and it helps keep the code more organized.

One of the challenges I am facing is with a promise that fetches user information from the database:

.service('userInfo', function ($http, $cookies) {
      var userId = $cookies.id;
      console.log("UI Cookies", $cookies);

    var promise = $http.get('/api/findProfile/' + userId, { cache: false}).
      success(function (data) {
          var userInfo = data;
          console.log("This is fresh data!") // This logs the first time I load my page, but never again
          return userInfo;
      }).error(function(data) {
          console.log("ERROR")
          return userInfo
      });
      return promise; 

})

When moving from one signup step to the next, I update the profile information in MongoDB and then load the subsequent page. However, when I navigate to a new page using $location('') from my controller, I notice that I receive outdated userInfo which has not been updated in the database. On the other hand, if I do a complete page refresh, I get the correct and updated userInfo.

Could this be a caching issue? Despite passing {cache: false} to my $http promise, I am unable to retrieve fresh data (as indicated by the

console.log("This is fresh data!")
); instead, I seem to be getting cached data.

Is there a way to resolve this without having to force a full-page reload in Angular?

Answer №1

It's not simply a matter of caching, as you might believe.

Angular services and factories act as singletons, meaning they are initialized once and then shared across all controllers without running the service function again. This ensures that all controllers receive the same object. (For services, the object is created using the service function as a constructor)

If you need to fetch data every time a view is loaded, you should initialize the request in a controller (which can be done through a service) - this controller will be re-initialized without reloading the browser page.


Furthermore, there are some issues with how you are handling promises and return values. Returning from error and success handlers is unnecessary, as their return values are not used. Refer to this discussion for more details on "returning" from asynchronous functions.

A cleaner approach would be to return the $http promise from a service function, allowing each controller to handle the promise appropriately. This simplifies your service code to the following:

.service('userInfo', function ($http, $cookies) {
  var userId = $cookies.id;
  console.log("UI Cookies", $cookies);

  //this function returns the promise returned by $http.get  
  this.getData = function(){
       return $http.get('/api/findProfile/' + userId, { cache: false});
  };
})

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

Achieve the same functionality as the nextjs getStaticProps() function across all pages without the need to duplicate the code on each page

Is there a way to implement the functionality of the nextjs getStaticProps() function for all pages without duplicating the code on each page? I have multiple pages and a layout component. I am looking to include a global function on all pages. Is it poss ...

Setting up Laravel Mix Vue.js source maps to display actual component code during debugging

My current setup includes Laravel 5.4 and Vue.js 2.6. I'm facing an issue with viewing the sourceMap of *.vue component files in the console. Here is how I've configured Laravel mix: let mix = require('laravel-mix'); mix.webpackConfig ...

What is the best way to fill HTML tables using an ajax response?

This is a Laravel blade view/page that requires updating without the need to refresh the entire page. The blade.php code functions correctly and retrieves data from a MySQL database, but there seems to be an issue with the AJAX and JavaScript implementati ...

As I enlarge the font size, the border around the div also expands

Can someone explain why the size of the div border increases along with the font size? If you'd like to see an example, check out this link to a jsFiddle: LINK TO JS FIDDLE: http://jsfiddle.net/krishna22211/m14qms52 ...

Is there a way to use regular expressions to search for class names within nested div elements?

I'm struggling to find nested divs like these in my document object model (DOM) <div class="two-columns some-other-class"> <div class="two-columns some-other-class"> </div> </div> I attempted to search for neste ...

Implementing a jQuery change event to filter a specific table is resulting in filtering every table displayed on the page

I have implemented a change event to filter a table on my webpage, but I am noticing that it is affecting every table on the page instead of just the intended one. Below is the code snippet: <script> $('#inputFilter').change(function() { ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

Filtering a JSON array with the PHP $_POST array

Currently, I am dealing with a json file that holds detailed vehicle information: array_filter, after selecting Ford, the Chevy vehicles are excluded from the results. So if I choose Ford and Red, I will only get one result as expected - a red Mustang. H ...

Delete the content on a webpage using an Ajax jQuery request to transfer it elsewhere

Whenever I submit a form using an ajax post request, I receive values from the controller and manipulate the page based on those values. However, my issue is that I need to erase the values from the previous request when the form is submitted again. For in ...

Leveraging RXJS for efficient data retrieval in nodejs

When dealing with sending a bulk of data and moving on to the next one upon completion, it can be quite challenging. Take for instance this function: async function test() { await sample.sampleStructure() await sample.sampleDataAdd() await sample.sa ...

Retrieve database SQL information using JavaScript to display data

I'm struggling to push the value from a textbox to SQL and display it. Despite reading numerous topics, I still can't figure it out. My explanation skills are lacking, but hopefully you can understand what I'm trying to achieve, especially i ...

Using the active class feature in React Router

Hey there! I've been working with react router v6 and using NavLink to move between components. I've been trying to figure out how to add a custom active class in NavLink, but the method I tried isn't working. Here is what I attempted: <N ...

What is the best way to avoid duplicating this JQM function multiple times and instead reuse it efficiently?

After coming across this interactive demo, I successfully implemented it on my website using JQM. However, in order to activate the panel swipe feature, I had to include the following function: $( document ).on( "pagecreate", "#demo-page", function() { ...

When using CSS float:left and overflow:visible, the text may get cropped-off at

I'm currently experimenting with creating a color gradient in javascript using numerical values within some of the divs to indicate scale. However, I've run into an issue where as the values get larger, they are cut off due to the float:left prop ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

Guide to presenting XML information from a web address using XSLT

I am currently working with dynamic XML sports data from a URL in a Yahoo API, and I want to display and sort a selection of this data on my website using XSLT. This is my first time dealing with XML and XSLT, and while testing, I have managed to correctly ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Using an arrow function in Aurelia to read a json file

I've been exploring Aurelia and delved into tutorials on PluralSight and Egghead.io, but I'm still struggling to resolve my current issue. In a JSON file named bob.json, there is a collection of objects related to Bob. Each object in the collect ...

Utilize the `addEventListener` and `removeEventListener` functions on the menu to

Why is my mobile menu not functioning correctly? The submenu should open on the first click and redirect to the parent URL on the second click, which works fine. However, when the window width increases to 768px or more, the submenu should appear on hover ...

Socket.io is most effective when reconnecting

I am currently in the process of developing a React application that connects to a Node.js API and I am trying to integrate the Socket.io library. Following various online tutorials, my code now looks like this: API: import express from 'express&apo ...