Jakob Abfalter Jakob Abfalter - 9 months ago 150
Javascript Question

WebSockets in angular2

I want to integrate a WebSocket client to my angular2 application.

I frist tried to do this using sock.js https://github.com/sockjs/sockjs-client
and created a SockJS object like this:

export class Core {

private sock: any;

constructor (private router: Router) {

this.sock = new SockJS(AppSettings.WEBSOCK_ENDPOINT);



My problem is that angular2 is unable to recognize the SockJS type.

I then tried to use the typings definition provided by https://github.com/retyped/sockjs-client-tsd-ambient/blob/master/sockjs-client.d.ts in my project, but couldn't really figure out where and how to set the typing up.

Alternatively I tried to use the angular2-websocket npm package https://github.com/afrad/angular2-websocket, but when I do this in my application:

import {$WebSocket} from 'angular2-websocket/angular2-websocket'
var ws = new $WebSocket("url");

My IDE (Jetbrains WebStorm) tells me that $WebSocket expects at least 2 parameters.

Since there is very little information out there about WebSockets in angular2 at the moment I decided to ask if someone could explain me a good and easy way to set up a WebSocket within an angular2 project.

I use angular2 + webpack and built my project on this boilerplate https://github.com/angular/angular2-seed


As you may see in


the other parameters are optional

constructor(private url:string, private protocols?:Array<string>, private config?: WebSocketConfig  ) {

you might also like this it has working socket angular example (using socket.io)