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

4

I have some issues with automatically updating a code in Angular.js inside my site. The integration is Node.js with HTML, integrating with Angular.js. However I have to always give F5 on the page so it updates the variable "Temperature". I would like to integrate into the system the automatic update, upon receiving the POST command on node.js

UPDATE 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 searched to integrate INTERVAL, an Angular module in this code, but I could not.

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

    
asked by anonymous 03.10.2016 / 21:04

1 answer

5

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

One important thing: Do not use the success and error functions, they are obsolete. Instead, use the then function. See the AngularJS documentation . I'll leave an example using then at the end of the answer.

Just so you know, you can actually make the connection real time 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 is referring to success and the second referring to error .

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

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

Update

It's important to tell you that by using $ interval, if one of the requests takes longer than the retry time (5 seconds in the example), the function will run again, which can cause problems. So I recommend calling the function within itself by combining with $timeout to delay execution of it. See more at Why do you say setTimeout recursion 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

});
    
03.10.2016 / 21:09