Atmosphere和Angular JS如何

时间:2015-05-06 06:50:24

标签: angularjs websocket atmosphere

我是一个氛围& Angular新手和我真的很难找到答案!也许我在问错误的问题。

我正在使用 Atmosphere 设置通知。如果我将API URL直接发布到浏览器中,我可以打开websocket并观察更新。

在Angular中我有一个 ng-repeat 循环,我想在每个新更新向websocket添加一个新对象时运行它。

<li ng-repeat="notification in notifications track by $index">

我正在使用角度观察来检查更新,但它没有选择要添加到阵列的新对象。这是我的代码:

// notification alerts
$scope.notifications = [];

notificationsService.notificationAlerts().then(function success(response) {                
    var jsonStringArray = response.data.split('|');
    $scope.notifications = $.map(jsonStringArray, function(n, i){
        if (n !== ""){
            return JSON.parse(n);
        }
    });
    console.log('Connect', response);               
});

$scope.$watch('notifications', function(newVal, oldVal){
    console.log('Watch', $scope.notifications);
}, true);

希望我已经说清楚了,如果我需要详细说明,或者我是否提出错误的问题,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:1)

好的,我设法解决了这个问题,对于后来遇到困难的人来说。这是最终的JS:

// add number of notifications to ".notifications-number"
function updateNumberOfNotifications(){
    var numberOfNotifications = $("ul.notifications-list li").not(".nocount").length;
    if (numberOfNotifications < 1) {
        $(".notifications-number, .notifications-list").addClass("hidden");
    } else {
        $(".notifications-number").html(numberOfNotifications);
        $(".notifications-number, .notifications-list").removeClass("hidden");
    }                
}            

// notification alert variables
$scope.notifications = [];
var socket = atmosphere;
var subSocket;

// subscribe
function subscribe() {
    var request = {
        url : "/service/notifier",
        transport: 'long-polling'
    };

    request.onMessage = function (response) {
        //console.log('response', response);
        var jsonStringArray = response.responseBody.split('|');
        // console.log('json string array', jsonStringArray);
        $.each(jsonStringArray, function(index, elem){
            if (elem != ""){
                $scope.notifications.push(JSON.parse(elem));
                console.log("object", JSON.parse(elem));
            }                        
        });
        //$scope.notifications.push($scope.newNotification);
        $scope.$apply();                  

        updateNumberOfNotifications();          

        // console.log('$scope.notifications', $scope.notifications);             
    };

    subSocket = socket.subscribe(request);
}

function unsubscribe(){
    socket.unsubscribe();
}

// subscribe on load and update notifications
updateNumberOfNotifications();
subscribe();