简体   繁体   English

值未使用socket.io在angularJS中自动更新

[英]Value not updating automatically in angularJS with socket.io

Following is my angularJS code with socket.io which is only fetching value when I switch from a view, though I was expecting it to update the value automatically. 以下是我的带有socket.io angularJS代码,虽然我希望它自动更新值,但仅在从视图切换时才获取值。 Let me know what I am doing wrong here - 让我知道我在做什么错-

angular.module("app").controller("DashboardController", function($scope, SessionService) {
    $scope.user = SessionService.currentUser;

  // Code for realtime notifications
  if (SessionService.currentUser._id) {
      var socket = io('http://localhost:6868');
          socket.emit('get notifications', {user_id: SessionService.currentUser._id});
      socket.on('notification data', function(data){
          $scope.$apply(function() {
              $scope.notificationCount = data.length;
          });
      });
  }     
});

I dont think you need to do $scope.$apply here. 我认为您不需要在这里执行$ scope。$ apply。 You can assign the new value without this. 您可以不使用该值分配新值。 Socket looks better here as an angularjs factory. 套接字在这里作为angularjs工厂看起来更好。

Look into this code to know how to use socket as a factory. 查看此代码,以了解如何将套接字用作工厂。

https://github.com/sojharo/Simplest-Mean/blob/master/public/javascripts/MyAngularApp.js https://github.com/sojharo/Simplest-Mean/blob/master/public/javascripts/MyAngularApp.js

Keep things separate 让事情分开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM