Jakob Nielsen
Jakob Nielsen

Reputation: 5198

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

Upvotes: 2

Views: 8985

Answers (2)

O.DO
O.DO

Reputation: 71

i also can recommend this implementation for websockets in angular2: https://github.com/Sinthor/WSM

Upvotes: 0

Jacek Pietal
Jacek Pietal

Reputation: 2019

As you may see in

https://github.com/afrad/angular2-websocket/blob/master/src/angular2-websocket.ts

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)

https://github.com/leonardohjines/auctionApp

Upvotes: 4

Related Questions