简体   繁体   English

Angular2 + Socket.IO实现最佳实践

[英]Angular2 + Socket.IO Implementation Best Practice

Currently I have a singleton (static-ish?) service that initializes the socket, and sets the events. 当前,我有一个单例(静态ish?)服务,用于初始化套接字并设置事件。 The service is then injected to each of the components that utilize socket information. 然后将服务注入使用套接字信息的每个组件。

My questions are: 我的问题是:

  • Does this sound like best practice? 这听起来像是最佳做法吗?

  • Can you forsee and issues? 您可以预见并发布问题吗?

  • Changes you might make? 您可能会做出改变?

I have only developed in angular 1.5.x, so I'm not sure how applicable my answer is, but perhaps you can take the design principals from it, and apply it properly, but here goes. 我仅在angular 1.5.x中进行开发,所以我不确定我的答案有多适用,但是也许您可以从中获取设计原理,并正确地应用它,但是到了。

My initial thought on how I would do this is this. 我最初对如何执行此操作的想法是。 I'd set up a socket service that handles things like initializing the socket, and would also have two public functions to bind an event, and unbind an event. 我将设置一个套接字服务来处理诸如初始化套接字之类的事情,并且还将具有两个公共函数来绑定事件和取消绑定事件。 The binding would take an event name, and a function which has a data parameter, and probably return an ID to unbind the event later, like this: 绑定将采用事件名称和具有数据参数的函数,并且可能返回一个ID以便以后取消绑定该事件,如下所示:

var bindingId = SocketService.bind('socketEventName', function(eventData){
    console.log(eventData);
});

and then to unbind you can just do this 然后解除绑定即可

SocketService.unbind(bindingId);

with this sort of layout, means that you can then include you SocketService in other services, and let the other services handle the response as they need to, rather than having all that logic in your SocketService. 使用这种布局,意味着您可以将SocketService包含在其他服务中,并让其他服务根据需要处理响应,而不是将所有逻辑包含在SocketService中。

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

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