具有服务器发送事件的AngularJS [英] AngularJS with Server-Sent Events

查看:106
本文介绍了具有服务器发送事件的AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下控制器的AngularJS应用程序。它可以在常规JSON资源和手动更新请求上使用GET,但我无法使用Server-Sent Events。我面临的问题是,在收到SSE事件并设置/更新openListingsReport变量后,我的视图没有得到更新。我显然错过了一个非常基本的概念。请帮我解决这个问题。

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;
    }
}]);


推荐答案

问题出在以下几行:

$scope.openListingsReport = event.data;

应该是:

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

这篇关于具有服务器发送事件的AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆