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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。