您好,登錄后才能下訂單哦!
Socket.io怎么在angular中使用?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
服務端(nodeJs/express):
let app = require('express')(); let http = require('http').Server(app); let io = require('socket.io')(http); io.on('connection', (socket) => { console.log('user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('add-message', (message) => { io.emit('message', {type:'new-message', text: message}); }); }); http.listen(5000, () => { console.log('started on port 5000'); });
客戶端,創建一個ChatService
import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import * as io from 'socket.io-client'; export class ChatService { private url = 'http://localhost:5000'; private socket; sendMessage(message){ this.socket.emit('add-message', message); } getMessages() { let observable = new Observable(observer => { this.socket = io(this.url); this.socket.on('message', (data) => { observer.next(data); }); return () => { this.socket.disconnect(); }; }) return observable; } }
ChatComponent
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Control } from '@angular/common'; import { ChatService } from './chat.service'; @Component({ moduleId: module.id, selector: 'chat', template: `<div *ngFor="let message of messages"> {{message.text}} </div> <input [(ngModel)]="message" /><button (click)="sendMessage()">Send</button>`, providers: [ChatService] }) export class ChatComponent implements OnInit, OnDestroy { messages = []; connection; message; constructor(private chatService:ChatService) {} sendMessage(){ this.chatService.sendMessage(this.message); this.message = ''; } ngOnInit() { this.connection = this.chatService.getMessages().subscribe(message => { this.messages.push(message); }) } ngOnDestroy() { this.connection.unsubscribe(); } }
關于Socket.io怎么在angular中使用問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。