The Techies' pub

Angular 2 – Sockets

In this post let us see how to use sockets in our Angular 2 apps. In one of my previous posts, I have shown how to use socket.io along with Ionic 2 framework. So, many of our friends have been asking me to do a post on how to use it along with angular 2 + typescript.

Once typings are installed open up angular-cli-build.js file and add our socket.io-client to the vendorNpmFiles as shown below.

1

2

3

4

5

6

7

8

9

10

vendorNpmFiles:[

'systemjs/dist/system-polyfills.js',

'systemjs/dist/system.src.js',

'socket.io-client/socket.io.js',

'zone.js/dist/**/*.+(js|js.map)',

'es6-shim/es6-shim.js',

'reflect-metadata/**/*.+(js|js.map)',

'rxjs/**/*.+(js|js.map)',

'@angular/**/*.+(js|js.map)'

]

Now open up system-config.ts file present in the src/app directory and modify the contents as shown below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

constbarrels:string[]=[

// Angular specific barrels.

'@angular/core',

'@angular/common',

'@angular/compiler',

'@angular/http',

'@angular/router',

'@angular/platform-browser',

'@angular/platform-browser-dynamic',

// Thirdparty barrels.

'rxjs',

'socket.io-client',

// App specific barrels.

'app',

'app/shared',

/** @cli-barrel */

];

constcliSystemConfigPackages:any={};

barrels.forEach((barrelName:string)=>{

if(barrelName=='socket.io-client')

cliSystemConfigPackages[barrelName]={main:'socket.io.js'}

else

cliSystemConfigPackages[barrelName]={main:'index'};

});

/** Type declaration for ambient System. */

declarevarSystem:any;

// Apply the CLI SystemJS configuration.

System.config({

map:{

'@angular':'vendor/@angular',

'rxjs':'vendor/rxjs',

'socket.io-client':'vendor/socket.io-client',

'main':'main.js'

},

packages:cliSystemConfigPackages

});

Why do we do this ? Well the app is structured in such a way that the dependencies are loaded into our index.html file while we build it. So in order to use the socket.io.js file we need to get it loaded into our index.html as well and that’s why we edit angular-cli-build.js and system-config.ts files respectively.

Now that this is done, open up our angular2socket.component.ts file and add the below code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import{Component}from'@angular/core';

import *asio from'socket.io-client';

import{Observable}from'rxjs/Observable';

import'rxjs/Rx';

@Component({

moduleId:module.id,

selector:'angular2socket-app',

templateUrl:'angular2socket.component.html',

styleUrls:['angular2socket.component.css']

})

exportclassAngular2socketAppComponent{

socket=null;

chatinp='';

constructor(){

this.socket=io('http://localhost:3000');

let listener=Observable.fromEvent(this.socket,'message');

listener.subscribe((payload)=>{

console.log(payload);})

}

send(msg){

this.socket.emit('message',msg);

}

}

Now this code does nothing but connect to the backend (specified url) and creates a socket. Then we use an observable for expressing the data stream that comes in through this socket.

Once a user subscribes to this datastream he can see the messages received in real-time.

The send method is used to emit messages which the user sends. To wire this up open up angular2socket.component.html file and add the below code.

1

2

<input type="text"[(ngModel)]="chatinp">

<button(click)="send(chatinp)">Send</button>

This will create a text input along with a button using which the user can send a message. Whichever message the user sends can be seen printed on the console in real-time since the user listens to the same flag in which he sends the message through.

So, this is how you use socket.io in your angular 2 + typescript apps and also make use of observables to handle a data stream from an event.