简体   繁体   English

在 Angular 应用中监听 socket.io

[英]Listen for socket.io in an Angular App

I'm looking to integrate socket.io with my angular app.我希望将 socket.io 与我的 angular 应用程序集成。 I've seen some examples of how to create a service, which makes it accessible on the controller.我已经看到了一些关于如何创建服务的例子,这使得它可以在控制器上访问。 Which I understand.我明白。 But I'm looking for a way that all the controllers can react to event calls from socket.io.但我正在寻找一种方法,让所有控制器都可以对来自 socket.io 的事件调用做出反应。

So:所以:

socket.on('user joined', function (data) {}); socket.on('用户加入', function (data) {});

I can do that in one controller but how do I do it for all?我可以在一个控制器中做到这一点,但我如何为所有人做到这一点?

You'll want to encapsulate your socket in a service and inject it into Angular controllers as needed .您需要将套接字封装在服务中,并根据需要将其注入 Angular 控制器

Let's make a socket service:让我们创建一个套接字服务:

app.factory('socket', function ($rootScope) {
  var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };
});

Then we'll inject into a controller and interact with it (through the socket.io API):然后我们将注入一个控制器并与之交互(通过socket.io API):

function AppCtrl($scope, socket) {
  socket.on('init', function (data) {
    $scope.name = data.name;
    $scope.users = data.users;
  });
}

You can obviously customize the controller to do what you need to with the socket service.您显然可以自定义控制器以使用套接字服务执行您需要的操作。

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

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