web-dev-qa-db-ja.com

angular 4でsocket.io-clientを使用する方法

サーバー側はphp laravel echo websocketであり、Angularで接続しようとしています。成功しました。誰かが私がそれをどのように使用できるかドキュメントまたはチュートリアルを知っているなら、助けてください

13

こんにちは、@ gigaの例を以下に示します。

[〜#〜] setup [〜#〜]

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

サーバー側(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);
});

クライアント側-Angular4コード

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 = '';
  }

}
27
VithuBati

セットアップ

npm install socket.io-client --save
npm install @types/socket.io-client --save-dev

サービスとして:

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

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

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

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

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

コンポーネント内:

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);
  }
}
18

さらに、インストールする必要があるVithuBatiの回答:npm i socket.io-client --save npm i @types/socket.io-client --save

1
David Dehghan

@ MA-Maddinのソリューションに従って、この実装を行いました。

サービスで: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);
   });
  })
 }
}

コンポーネントで

 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);
  }
}

これにより、バインディングが正しく更新されます。

1
Richard Aguirre