AngularJS with Server-Sent Events

帅比萌擦擦* 提交于 2019-12-20 09:20:14

问题


I have an AngularJS app with the following controller. It worked fine with GET on regular JSON resource and manual request for updates, but I cannot make it work with Server-Sent Events. The problem I am facing is that after I receive an SSE event and set/update openListingsReport variable my view is not getting updated. I am obviously missing a very basic concept. Please help me fix this.

var rpCtrl = angular.module('rpCtrl', ['rpSvc']);

rpCtrl.controller('rpOpenListingsCtrl', ['$scope', 'rpOpenListingsSvc',
    function ($scope, rpOpenListingsSvc) {
        $scope.updating = false;

        if (typeof(EventSource) !== "undefined") {
            // Yes! Server-sent events support!
            var source = new EventSource('/listings/events');

            source.onmessage = function (event) {
                $scope.openListingsReport = event.data;
                $scope.$apply();
                console.log($scope.openListingsReport);
            };
        }
    } else {
        // Sorry! No server-sent events support..
        alert('SSE not supported by browser.');
    }

    $scope.update = function () {
        $scope.updateTime = Date.now();
        $scope.updating = true;
        rpOpenListingsSvc.update();
    }

    $scope.reset = function () {
        $scope.updating = false;
    }
}]);

回答1:


The problem was in the following line:

$scope.openListingsReport = event.data;

which should be:

$scope.openListingsReport = JSON.parse(event.data);



回答2:


Just a suggestion in case someone is using SSE with AngularJs.

If you want to use server side events ,I will suggest to use $interval service that is builtin within AngularJS instead SSE.

Below is the basic example.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

    <p>Randome no:</p>

    <h1>{{myWelcome}}</h1>

</div>

<p>The $interval service runs a function every specified millisecond.</p>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, $interval, $http) {
        $scope.myWelcome = new Date().toLocaleTimeString();
        $interval(function () {
            $scope.myWelcome = $http.get("test1.php").then(function (response) {
                $scope.myWelcome = response.data;
            });
        }, 3000);
    });
</script>

</body>
</html>

test1.php

<?php

echo rand(0,100000);


来源:https://stackoverflow.com/questions/25166770/angularjs-with-server-sent-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!