How to use socket.io-client in angular 4
Asked Answered
P

5

18

Server side is php laravel echo websocket and I am trying to connect by Angular 4. I tried using ng2-socket-io - npm and also laravel-echo - npm but none of them were successfully. If anyone know any documentation or tutorial how I can use it, please help

Permenter answered 7/11, 2017 at 15:27 Comment(0)
H
38

Hi @giga Working example is given below.

SETUP

npm i socket.io-client --save
npm i @types/socket.io-client --save

Server-side (nodejs)

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var port = 8000;

app.use(express.static(path.join(__dirname, "public")));

io.on('connection', (socket) => {
console.log('new connection made');

socket.on('event1', (data) => {
  console.log(data.msg);
});

socket.emit('event2', {
  msg: 'Server to client, do you read me? Over.'
});

socket.on('event3', (data) => {
  console.log(data.msg);
  socket.emit('event4', {
    msg: 'Loud and clear :)'
  });
});
});

server.listen(port, () => {
  console.log("Listening on port " + port);
});

Client-side - Angular4 code

import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';

@Component({
    moduleId: module.id,
    selector: 'ch-home',
    styleUrls: ['home.styles.css'],
    templateUrl: 'home.template.html'
})

export class HomeComponent implements OnInit {
    messageText: string;
    messages: Array<any>;
    socket: SocketIOClient.Socket;

  constructor() {
   // this.socket = io.connect('http://localhost:8000');
   this.socket = io.connect();
  }

  ngOnInit() {
        this.messages = new Array();

        this.socket.on('message-received', (msg: any) => {
            this.messages.push(msg);
            console.log(msg);
            console.log(this.messages);
        });
      this.socket.emit('event1', {
          msg: 'Client to server, can you hear me server?'
      });
      this.socket.on('event2', (data: any) => {
        console.log(data.msg);
        this.socket.emit('event3', {
            msg: 'Yes, its working for me!!'
        });
      });
      this.socket.on('event4', (data: any) => {
          console.log(data.msg);
      });
   }

   sendMessage() {
    const message = {
      text: this.messageText
    };
    this.socket.emit('send-message', message);
    // console.log(message.text);
    this.messageText = '';
  }

}
Holzer answered 7/11, 2017 at 15:56 Comment(7)
Thank you that was helpfullPermenter
#52702554 can u help for this questionArithmetician
@GigaSongulashvili hey, how did you connect it with laravel?Lindemann
@VithuBati, what are the event1,event2,event3,event4 ? are they function names ? Like a function ( or a method ) you created that has http request ?Goar
i did like this but i have problem updating my chat template, socket-io on Events not update my template correctlyAutolysin
Nevermind response from @MA-Maddin solve my problem and i think is the correct way to implement socket- io on Angular.Autolysin
hello, here i found somebody has already implemented socket.io, may please check my code and tell me what is the problem? #56963876Borlase
D
31

Implement socket.io-client as an Angular service

Setup

npm install socket.io-client --save

Note (since Socket.IO v3):
Do not install @types/socket.io-client since the types are now included in the socket.io-client package. So you will face problems if you install them additionally (source).

The service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io, Socket } from 'socket.io-client';

@Injectable()
export class ChatService {
  private socket: Socket;

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

  // EMITTER example
  sendMessage(msg: string) {
    this.socket.emit('sendMessage', { message: msg });
  }

  // HANDLER example
  onNewMessage() {
    return new Observable(observer => {
      this.socket.on('newMessage', msg => {
        observer.next(msg);
      });
    });
  }
}

In a component:

import { Component, OnInit } from '@angular/core';
import { ChatService } from './chat-service';

@Component({
  // ...blabla...
})
export class ChatComponent implements OnInit {
  msgInput: string = 'lorem ipsum';

  constructor(
    private chatService: ChatService,
  ) { }

  ngOnInit() {
    this.chatService.onNewMessage().subscribe(msg => {
      console.log('got a msg: ' + msg);
    });
  }

  sendButtonClick() {
    this.chatService.sendMessage(this.msgInput);
  }
}
Dyslogia answered 18/1, 2018 at 20:44 Comment(3)
sendMessage(msg: string) { this.socket.emit('sendMessage', { message: msg }); } How can i send acknowledgment here?Pskov
This is the correct implementation of socket-io because the first one dont work good when updating the data in component's templatesAutolysin
hello, here i found somebody has already implemented socket.io, may please check my code and tell me what is the problem? #56963876Borlase
A
4

Following the solution of @MA-Maddin, I did this implementation:

at Service:socket.service

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SocketService {
private socket:SocketIOClient.Socket;

constructor() { 
  this.socket=io('http://localhost:3300');
}
emit(event:string, data:any){
  this.socket.emit(event,data);
}
on(event:string){
  return Observable.create(observer=>{
   this.socket.on(event,data=>{
    observer.next(data);
   });
  })
 }
}

At Component

 import { Component, OnInit, Input, ViewChild, ViewEncapsulation} from 
'@angular/core';
import { AuthService } from 'src/app/auth/auth.service';
import Socket from '../../services/socket.service';

@Component({
  selector: 'app-lobby-chat',
  templateUrl: './lobby-chat.component.html',
  styleUrls: ['./lobby-chat.component.css'],
  encapsulation: ViewEncapsulation.None,
})
export class LobbyChatComponent implements OnInit {
  constructor(private socket:Socket) {
  this.socket.on('getMessage').subscribe(data=>{
  console.log(data);
  });
  }
  pushMessage(msg){
  this.socket.emit('sendMessage',msg);
  }
}

This will update your bindings correctly. Note: **use npm i "@types/socket.io-client for use or define Socket io Types **

Autolysin answered 18/4, 2019 at 23:3 Comment(5)
hello, here i found somebody has already implemented socket.io, may please check my code and tell me what is the problem? #56963876Borlase
FYI: Observer.create() is deprecated.Arathorn
private socket:SocketIOClient.Socket; this line gives error? any solutionsPerfection
estas haciendo algo que no entiendo, private socket:SocketIOClient.Socket; de donde estas trayendo el SocketIOClient ??????????Electrolyze
@Electrolyze instala los types de socket con el comando "npm i @types/socket.io-client"Autolysin
C
3

I know its an old question , For me none of the solutions worked so I solved with below approach.

Do Not Waste your time if your socket connection polling is working fine and not getting any error , It might be due to the socket.io.client package conflict with your other setup

my application version are below.

Angular 12.x Socket.io.client 4.x Node 14.16.1 I also tried with ngx-socket-io package too that also didn't work. the strange part is socket.io poling works well hand shaking are correct but not able to listen the event on new messages.

So my final approach is adding socket.io manully to index.html of angular and dispatch and event to the compoent.

function RsCustomEvent ( event, message ) {
    params = { bubbles: false, cancelable: false, detail: message };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}
var socket = io('localhost:3000');
socket.on("channel-name", function (message) {
    window.dispatchEvent(RsCustomEvent('socketEventListen',message));

});

then in the angular component I used below codes.

 import { Observable , fromEvent} from 'rxjs';


fromEvent(window, 'socketEventListen').subscribe((data) =>{
 });

manually download the socket.io client js file and place that in asset folder and use the above codes.

Clever answered 29/10, 2021 at 8:26 Comment(0)
M
2

In addition the VithuBati's answer you need to install: npm i socket.io-client --save npm i @types/socket.io-client --save

Moresque answered 9/3, 2018 at 18:50 Comment(3)
So I have to run the second cmd too? The "SocketIOClient.Socket" namespace is not found in my project...Harveyharvie
Yep. the second is needed.Harveyharvie
hello, here i found somebody has already implemented socket.io, may please check my code and tell me what is the problem? #56963876Borlase

© 2022 - 2024 — McMap. All rights reserved.