What is this error that I get when I use socket.io?

0

I have created a API that uses socket.io :

const socketIo = require('socket.io');
const serverHttps = https.createServer(httpsOptions, 
app).listen(httpsPort, () => { 
console.log('HTTPS: Server running at ' +  
httpsPort)});
const io = socketIo(serverHttps);
io.on('connection', (socket)=> { 
socket.emit('hello', { greeting: 'Hola 
George'}); 
 });

And this API consumption from Angular where I have also implemented socket.io.

When you start in the method ngOnInit to connect to API through socket:

import * as socketIo from 'socket.io';
const socket = socketIo('https://192.168.120.201:8950');

I'm getting this error

  

WARNING in ./node_modules/socket.io/lib/index.js   108: 11-32 Critical dependency: the request of a dependency is an expression

Any idea what it might be?

Do I need to install another library?

    
asked by JGuerra 21.03.2018 в 19:08
source

1 answer

2

To use socket.io from angle you should use socket.io-client

npm install --save socket.io-client

As a good practice you should use it from a service, and you could use observables to handle the "on" events of socket.io an example of this would be this

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

// socket.io
import * as io from 'socket.io-client';

// rxjs
import { Observable } from 'rxjs/Observable';

@Injectable()
export class SocketService {

    socket: any;
    url:string = 'http://api.socket';
    constructor() { }

    connect(): void {
        this.socket = io.connect(this.url);
    }

    disconnect(): void {
        this.socket.disconnect();
    }

    isConnect(): boolean {
        if (this.socket) {
            return this.socket.connected;
        }
        return false
    }

    /**
     *
     * @param eventName
     */
    on(eventName: string): Observable<any> {
        return new Observable(observer => {
            if (this.socket) {
                this.socket.on(eventName, data => observer.next(data))
            }
        });
    }

    /**
     *
     * @param emitName
     * @param data
     */
    emit(emitName: string, data?: any) {
        if (this.socket) {
            this.socket.emit(emitName, data);
        }
    }

}

and now you would only call connect from the ngOnInit () of the component where you want to use it

    
answered by 21.03.2018 / 19:31
source