简体   繁体   中英

Angular2 + Socket.IO Implementation Best Practice

Currently I have a singleton (static-ish?) service that initializes the socket, and sets the events. 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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