Update data automatically in AngularJS only when fresh data is retrieved from the server

I'm still learning AngularJS and I have a specific question regarding page refresh only when new data is fetched from the server.

I've looked for solutions online, but haven't come across anything that fits my issue.

Below is my Service and Controller with an intervalPromise setup:

MyService

angular.module('MyService', ['ngResource']).
    factory('Data', function($resource){
      return $resource('rest/getMyData', {});
});

MyController

function MyController($scope,$interval,$http, Data) {

    $scope.refresh = function() {
        $scope.jobs = Data.query();
    };

    $scope.intervalPromise = $interval(function(){
          $scope.refresh();
    }, 10000);  

    // initial load of data
    $scope.refresh();
}

The data is successfully retrieved from the server every 10 seconds, but I want to trigger a page refresh only if there's new data available.

Any guidance on how to achieve this would be highly appreciated.

Answer №1

To ensure accuracy, you can compare the information received from the server with your current dataset ($scope.jobs) and only make changes to $scope.jobs if there are discrepancies.

function MyController($scope,$interval,$http, Data) {

    $scope.refresh = function() {
        var serverData = Data.query();
        if( serverData !== $scope.jobs ) {
            $scope.jobs = serverData;
        }
    };

    $scope.intervalPromise = $interval(function(){
          $scope.refresh();
    }, 10000);  

    // initial load of data
    $scope.refresh();
}

Answer №2

I have stumbled upon a solution that seems to be effective.

Unlike Ryan's answer, which didn't work for me either, it appears that the issue lies in the timing of the Data.query() operation. It takes a brief moment to return, and this leads to a situation where the comparison in the if(...) statement is triggered prematurely. As a result, the screen keeps refreshing every ten seconds without any changes.

To address this issue, it is necessary to introduce a delay using setTimeout().

function MyController($scope,$interval,$http, Data) {
  $scope.refresh = function() {
      var serverData = Data.query();
      setTimeout(function(){
            if (serverData !== $scope.jobs){
               $scope.jobs = serverData;
            }
      }, 100);
  };

  $scope.intervalPromise = $interval(function(){
      $scope.refresh();
  }, 10000);  

  // initial load of data
  $scope.refresh();
}

This approach has proved to be effective for me, so it may be beneficial for anyone still struggling with similar issues.

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

Utilize JavaScript to randomly choose images as background tiles in HTML

Currently, I am in the process of developing a game using HTML/CSS/JavaScript. My background is currently set to a single image (100px / 100px) being repeated vertically and horizontally to tile across the entire page body; CSS: body { background-ima ...

What is the reason for an event triggering on a parent element before its child element when using a descendant selector?

I encountered a strange issue in my code where the event on a parent element seemed to trigger before the event on its child, rendering my e.stopPropagation() ineffective. Demo: $(document).ready(function() { // Directly binding events to the elemen ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

Find a specific row in a table using jQuery without requiring any input from the

I want to create a search function that filters results in a table based on user input. The script I have currently works but I need it to only search the first column without requiring the user to click an input field. I want the default value to load whe ...

Injection of dependencies in ui.bootstrap

For some reason, the ui.bootstrap dependency injection is causing all the content on my single page to disappear. There are no errors showing up in the console log, and I'm not sure why it's happening. I followed all the necessary steps, but I th ...

This piece of code is causing my browser to lag

I am encountering an issue with fetching and adding values from a weather API to my HTML elements. My goal is to display the hourly forecast for today, starting from the current hour until midnight of the next day. In order to optimize space, I implemente ...

Error messages from the Outlook Web add-in are presented as helpful information

I need assistance in showing error notifications. Here is my code: Office.context.mailbox.item.notificationMessages.addAsync("error", { type: "errorMessage", message: "The add-in encountered an issue while processing this message." }) The respons ...

Create an Oval-Shaped Image Cutout

Currently, I have a fabric.JS canvas where objects can be added. However, I am interested in clipping these objects into an oval shape, similar to the clip demos on fabricjs.com. In my current project (JSFiddle), I have been able to crop the object into a ...

What is the method to identify which event is activated when interacting with a button on a web browser?

Currently utilizing vue, bootstrap 4, and bootstrap-vue. My main objective is to resolve a visual glitch that emerges when I interact with a button (refer to the animated screenshot provided). This issue is evident at the bottom of the table, where unwant ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Kineticjs is not performing up to par

I apologize if this question has already been asked, but I haven't been able to locate it. I am working on a project that involves a canvas displaying approximately 400-500 rectangles, each ranging in height and width from 20-30 pixels. The goal is t ...

Rearrange the location of the displayed pathway within a document feature

In the process of uploading an image on my website, I have utilized a file field. When I select an image by browsing, the path of the image is displayed in the field. However, in Internet Explorer (IE), the path shifts down making it difficult to read. H ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

Revamp the HTML page by automatically refreshing labels upon every Get request

My HTML webpage requires real-time updates for one or more labels. To achieve this, I have incorporated CSS and JS animations into the design. Currently, I am utilizing Flask to handle all the calls. I face a challenge where I need to consistently update ...

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

Utilize Vue-cli 3.x to load static resources

In my vue-cli 3 project, I have organized the static assets in the public directory. When compiled and built on localhost, all assets load successfully, except for some images not appearing in the browser. Despite guyana-live-logo.png, slide-1.jpg, and 97 ...

What is the best way to fill in references that are nested within an array object using mongoose?

How do I go about populating the product fields within the cart array provided below? { "_id": "5bbd1c6e2c48f512fcd733b4", "cart": [ { "count": 1, "_id": "5bbd30ed9417363f345b15fc", "product": "5ba93a6d ...

Check the value of a single bit in JavaScript: Is the bit on (1) or off (0)?

Is there a way in JavaScript to determine if a single Bit is On (1) or Off (0)? function isBitOn(number, index) { // ... ? } // Example: let num = 13; // 1101 isBitOn(num, 0); // true 1 isBitOn(num, 1); // false 0 isBitOn(num, 2); // true 1 isBit ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Tips for eliminating duplicate values from an array

In my NodeJS code, I am currently comparing values in an array. The issue at hand is: I start with an empty array: var items = []; then proceed to insert some values into it: items[0] = {a:1, b:222}; items[1] = {a:1, b:333}; items[2] = {a:1, b:222}; ...