javascript 带有服务器发送事件的 AngularJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25166770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS with Server-Sent Events
提问by krl
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.
我有一个带有以下控制器的 AngularJS 应用程序。它适用于常规 JSON 资源的 GET 和手动更新请求,但我无法使其与服务器发送的事件一起使用。我面临的问题是,在我收到 SSE 事件并设置/更新 openListingsReport 变量后,我的视图没有得到更新。我显然缺少一个非常基本的概念。请帮我解决这个问题。
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;
}
}]);
采纳答案by krl
The problem was in the following line:
问题出在以下行中:
$scope.openListingsReport = event.data;
which should be:
应该是:
$scope.openListingsReport = JSON.parse(event.data);
回答by Vaibs
Just a suggestion in case someone is using SSE with AngularJs.
只是一个建议,以防有人将 SSE 与 AngularJs 一起使用。
If you want to use server side events ,I will suggest to use $interval service that is builtin within AngularJS instead SSE.
如果你想使用服务器端事件,我会建议使用 AngularJS 中内置的 $interval 服务而不是 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
测试1.php
<?php
echo rand(0,100000);