Integrating HTML + Node.js with Angular.js in "Real Time"

Asked

Viewed 858 times

4

I’m having some problems automatically updating a code in Angular.js within my site. The integration is Node.js with HTML, integrating with Angular.js. But I always have to give F5 on the page for it to update the variable "Temperature". I would like to integrate the automatic update into the system, when receiving the POST command on Node.js

UPDATING index.html

<html lang="pt-br" ng-app="angular">
<div ng-controller="myController">{{data}}</div>

<script>
        var app = angular.module('angular',[]);
app.controller('myController', function($scope, $http, $interval) {
$scope.data = [];

getData();

function getData () {

    var request = $http.get('/Temperatura');

    request.then(function(data) {
        $scope.data = data + " ºC";
    },function(data){
        console.log('Error: ' + data);
    });

    request.finally(function () {
        $timeout(5000, getData);
    });
    // O finally é executado sempre que a requisição terminar de executar, independente se o retorno for sucesso ou erro

});
</script>

Node.js

app.post('/EnviaTemperatura', function(req, res){
    temperatura = req.body.temp;
    res.send('Temperatura: ' + temperatura);
});

app.get('/Temperatura', function(req, res){
    res.send(temperatura);
});

I researched to integrate INTERVAL, an Angular module in this code, but I could not.

How can I turn my project into "Real Time"?

1 answer

5


Use the $interval to repeat the query in a time interval.

An important thing: do not use the functions success and error, they are obsolete. Instead they should use the function then. See the Angularjs documentation. I’ll leave an example using then at the end of the reply.

Just for you to have science, it’s possible to make the connection be real team actually, using Websockets, but this is not the subject of the question.

Example:

<script>
    var app = angular.module('angularjsNodejsTutorial',[]);
    app.controller('myController', function($scope, $http, $interval) {
        $scope.data = [];

        $interval(function(){
            var request = $http.get('/data');    
            request.success(function(data) {
                $scope.data = data + " ºC";
            })
            .error(function(data){
                console.log('Error: ' + data);
            });
        }, 5000); 

        /* O segundo parâmetro "5000", diz que a função deve ser repetida a cada 
           5000 milisegundos (5 segundos) */

    });
</script>

Code without the use of success and error. Here the first callback refers to the success and the second concerning error.

$interval(function(){
    var request = $http.get('/data');    

     request.then(function(data) {
                $scope.data = data + " ºC";
            },function(data){
                console.log('Error: ' + data);
            });
        }, 5000); 

Updating

It is important to tell you that, using $interval, if one of the requests takes longer than the repetition time (5 seconds in the example), the function will run again, which can cause you problems. So I recommend calling the function within itself combining with the use of $timeout to delay its execution. See more in Why do they say that recursive setTimeout is better than setInterval?

app.controller('myController', function($scope, $http, $interval) {
    $scope.data = [];

    getData();

    function getData () {

        var request = $http.get('/data');

        request.then(function(data) {
            $scope.data = data + " ºC";
        },function(data){
            console.log('Error: ' + data);
        });

        request.finally(function () {
            $timeout(5000, getData);
        });
        // O finally é executado sempre que a requisição terminar de executar, independente se o retorno for sucesso ou erro

});
  • Only complementing, if something is modified within the $Scope function is necessary to use $scope.apply()

  • worked out! Thanks! Why Websocket is better? I’m trying to find a better solution for me. I was testing in Socket i.o, now I’m jumping to Angular.js and I would like to have a better Real Time process. Which indicates?

  • It has advantages and disadvantages @Luizhenrique. You’ll have to understand well what you need and how Websocket works to decide what is best. An important thing (this is not just for this question), you can always mark one of the answers as correct for your questions by clicking on below the arrows to vote.

  • Depending on your scope, it is best to use $Digest() instead of $apply(). Just a complementary tip =D

  • @jbueno I know it’s not the topic question, but if I want to change this code to only run when the GET method changes? Like, I sent 100 to GET/date, can it update again only when I change this value? When I send 80, for example.

  • You say when the server return is a certain value other than the previous one?

  • @jbueno.

  • @jbueno the idea is to make the client receive the data only when you have a new POST command.

  • Okay, understood. And what’s the reason to update only when the value is different? Is it because you don’t want to make requests for no reason (not to cause any overhead) or because the display in the view flashes every time the value is changed? I ask this because for each case is a different answer.

  • @jbueno is actually the 2 reasons, because as in another process it will simulate something in Real Time, I’m trying to find out if the best solution is via Angular or via Socket

  • @jbueno I changed the code again according to the last one you sent, but presented the message below to me: Error: [$injector:nomod] Module 'angular' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the Second argument.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.