Tips for creating a binding between an HTTP service and a variable in AngularJS that adjusts when the server data is modified

Using an http get request in angular to extract data into an object with the users currently connected to my app requires refreshing the information every time for binding to the scope. To achieve this, I implemented a method to refresh the data from the array in the get request every 3 seconds:

index.jade

a(ng-repeat="item in room.connected")
img(src="/images/{{item.avatar}}")

controller.js

ngApp.controller('controller', function(){

   var vm = this;  vm.connected;

   $interval(function(){
   //The Get request returns an array like->[{"username":"cesarodriguez4","avatar":"icon-user-man-1.png"}]
   $http.get('http://localhost:3000/get-classroom-viewers/user')
   .then(function(response){
         vm.connected = response.data;
         },function(error){
         console.log(error);
        });
     }, 3000);
   //Executes the GET request every 3 seconds.
   });

While this solution works, it may not be optimal as the terminal shows the get request execution message every time. Is there a better method to refresh the data only when the server updates its information? I attempted using $scope.$watch but encountered issues.

Answer №1

To ensure real-time updates from the server, it is recommended to utilize websockets. By implementing websockets, any changes on the server side can be pushed to sockets which in turn can update the scope variable. This approach is more efficient than constantly looping or making server requests every few seconds, as it puts less strain on the server.

Implementing SockJS Angular Client

angular.module('myApp')
.service('PushNotificationService', ['$q', '$timeout', function($q, $timeout) {

   var service = {}, listener = $q.defer(), socket = {
      client: null,
      stomp: null
    };

    service.RECONNECT_TIMEOUT = 30000;
    service.SOCKET_URL = 'your socket Url'; // like '/chat'
    service.CHAT_TOPIC = 'topic url'; // like '/getMessage/chat'  

    service.receive = function() {
      return listener.promise;
    };

    var reconnect = function() {
      $timeout(function() {
        initialize();
      }, this.RECONNECT_TIMEOUT);
    };


    var startListener = function() {
      socket.stomp.subscribe(service.CHAT_TOPIC, function(data) {                 
          var jsonObj = JSON.parse(data.body);
        listener.notify(jsonObj);
      });
    };

    var initialize = function() {
      socket.client = new SockJS(service.SOCKET_URL);
      socket.stomp = Stomp.over(socket.client);
      socket.stomp.connect({}, startListener);
      socket.stomp.onclose = reconnect;
    };

    initialize();
    return service;
}]);

Incorporate the following code in your controller:

angular.module('myApp').controller('myCtrl', function($scope, PushNotificationService) {
     PushNotificationService.receive().then(null, null, function(message) {

                   //message has the data pushed to the socket from the server

            //assign data to $scope variable
          $scope.data = message;
                });
})

Add the below scripts to your HTML file:

sockjs.js
stomp.js

For further details, visit:

Websocket using Spring AngularJS SockJS

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

Map failing to refresh

Having some trouble with the map function as it's not updating my select box with the new selected value. The issue occurs within a material UI dialog that appears when viewing a file. I notice that the values get updated only after closing and reopen ...

Is there a way to incorporate pseudo-dynamic css into my projects?

I'm struggling with managing custom colored elements on my website. For instance, I have a hundred navigation squares on the site, each with its own unique color. The only solution I can think of is creating separate CSS classes for each color, but t ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts. I attempted adding transition: height 0.2s ease to the div, but it didn't work as expecte ...

Activate on click using JavaScript

When a link with the class .active is clicked, I want to use a JavaScript function to deactivate any other active links. The structure of the code should be as follows: <ul class="product"> <li><a href="#myanmar" class="active">Mya ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Inquiry on integrating Spotify with Axios for my debut solo project (beginner inquiry)

I have a question regarding my first solo project in React. I started learning code in September and I'm facing an issue while making a POST request to the Spotify API to retrieve an access token: Despite following the recommended 'Content-Type& ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Streamlining the login process in AngularJS to eliminate the need for repeated logins

I have set up authentication and authorization using AngularJS, Jersey REST, and Spring Security. Once a user logs in, they can call the "create" method below to save their information: .factory('Session', function () { this.create = functio ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

"Executing ng-click directive on a second click changes the route in AngularJS

Why does my ng-click only redirect to a new location on the second click? It should redirect to $location.path('/login.signin');, but it only works if I click the button again. It's strange. Where could this issue be originating from? Belo ...

Testing the Angular module's run function with unit tests

For our project, we have implemented requirejs along with angularjs. Our main application module is named 'app' and we have separate modules for services (app-services), controllers (app-controllers), filters (app-filters), etc. These modules are ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

Error encountered when trying to update Express Mongoose due to duplicate key

In my MongoDB database, I have a unique field called mail. When attempting to update a user, I encounter an issue where if I do not change the mail field, it triggers a duplicate key error. I need a solution where it is not mandatory to always modify the ...