MEAN stack和socket.io,表达式评估得太快

时间:2022-06-25 16:06:21

I'm having a hard time using angular and socket.io. When accessing a page I'm connecting to the server (Node.js) using socket.io. The server pulls data from mongoDB, then sends the data back to the client-side written in angular, which in turn should display the data using ng-repeat.

我在使用angular和socket.io时遇到了困难。访问页面时,我使用socket.io连接到服务器(Node.js)。服务器从mongoDB中提取数据,然后将数据发送回以角度写入的客户端,然后使用ng-repeat显示数据。

admin.hjs:

<body ng-controller="MainCtrl as mc">
   <H1>Admin</H1>
   {{mc.msgs.length}}
   {{mc.msgs}}
   <div ng-repeat="msg in mc.msgs">
       {{msg.name}}
   </div>
</body>

app.js:

(function() {
var app = angular.module('msgsSystem', []);

app.controller('MainCtrl', function(){
    var ctr = this;
    ctr.msgs = [];
    var socket = io.connect();
    //when receiving the msgs from the server
    socket.on('getMsgs', function(data){
        ctr.msgs = data;
        console.log('gotMsgs');
        console.log(ctr.msgs.length);
    });
  });
})();

When accessing the page I see that {{mc.msgs.length}} {{mc.msgs}} getting evaluated to 0 [], but in the console gotMsgs 6. My guess is that the page is rendering before the response comes back from the server.

访问该页面时,我看到{{mc.msgs.length}} {{mc.msgs}}被评估为0 [],但是在控制台中得到了这个6.我的猜测是在响应回来之前页面正在呈现从服务器。

I'd appreciate any help.

我很感激任何帮助。

1 个解决方案

#1


AngularJs does not work properly if you update scope variables in asynchronous methods (sockets, ajax). $scope.$apply() solves this issue.

如果在异步方法(套接字,ajax)中更新范围变量,AngularJs无法正常工作。 $ scope。$ apply()解决了这个问题。

app.controller('MainCtrl', function($scope){
    $scope.msgs = [];
    var socket = io.connect();
    //when receiving the msgs from the server
    socket.on('getMsgs', function(data){
        $scope.msgs = data;
        $scope.$apply();
    });
  });
})();

#1


AngularJs does not work properly if you update scope variables in asynchronous methods (sockets, ajax). $scope.$apply() solves this issue.

如果在异步方法(套接字,ajax)中更新范围变量,AngularJs无法正常工作。 $ scope。$ apply()解决了这个问题。

app.controller('MainCtrl', function($scope){
    $scope.msgs = [];
    var socket = io.connect();
    //when receiving the msgs from the server
    socket.on('getMsgs', function(data){
        $scope.msgs = data;
        $scope.$apply();
    });
  });
})();