Can AngularJS auto-update a view if a persistent model (server database) is changed by an external app?

后端 未结 5 1404
旧时难觅i
旧时难觅i 2020-12-07 07:32

I\'m just starting to familiarize with AngularJS, but I would like to build a web app that has a view that gets auto-upated in real-time (no refresh) for the user when somet

5条回答
  •  醉梦人生
    2020-12-07 07:46

    Here's an implementation that uses jetty instead node. The angularjs part is based on the angular-seed app. I'm not sure if the angular code is idiomatic...but I've tested that this works. HTH -Todd.

    TimerWebSocketServlet see

    https://gist.github.com/3047812

    controllers.js

    // -------------------------------------------------------------
    // TimerCtrl
    // -------------------------------------------------------------
    function TimerCtrl($scope, CurrentTime) {
        $scope.CurrentTime = CurrentTime;
        $scope.CurrentTime.setOnMessageCB(
            function (m) {
                console.log("message invoked in CurrentTimeCB: " + m);
                console.log(m);
                $scope.$apply(function(){
                    $scope.currentTime = m.data;
                })
            });
    }
    TimerCtrl.$inject = ['$scope', 'CurrentTime'];
    

    services.js

    angular.module('TimerService', [], function ($provide) {
        $provide.factory('CurrentTime', function () {
            var onOpenCB, onCloseCB, onMessageCB;
            var location = "ws://localhost:8888/api/timer"
            var ws = new WebSocket(location);
            ws.onopen = function () {
                if(onOpenCB !== undefined)
                {
                    onOpenCB();
                }
            };
            ws.onclose = function () {
                if(onCloseCB !== undefined)
                {
                    onCloseCB();
                }
            };
            ws.onmessage = function (m) {
                console.log(m);
                onMessageCB(m);
            };
    
            return{
                setOnOpenCB: function(cb){
                   onOpenCB = cb;
                },
                setOnCloseCB: function(cb){
                    onCloseCB = cb;
                },
                setOnMessageCB: function(cb){
                    onMessageCB = cb;
                }
            };
        })});
    

    web.xml

    
        TimerServlet
        TimerWebSocketServlet
        0
    
    
        TimerServlet
        /api/timer/*
    
    

提交回复
热议问题