1.安装
npm install express socket.io socket.io-client
版本:"express": "^4.17.1",
"socket.io": "^1.7.4",
"socket.io-client": "^1.7.4",
2.编写后台服务
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: { // 处理跨域问题
origin: "http://localhost:4300", // angular项目的启动端口,默认4200,本人项目的启动端口为4300,大家根据自己情况修改
methods: ["GET", "POST"],
credentials: true
}
});
io.on('connection', (socket) => {
console.log('user connected');
socket.on('add-message', (message) => {
io.emit('message', {type: 'new-message', text: message});
});
})
http.listen(4000, () => { // 后台服务启动端口
console.log('start on 4000....');
})
3.创建angular服务
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import * as io from 'socket.io-client';
@Injectable()
export class ChatService {
private url = 'http://localhost:4000'; // 后台服务端口
private socket: any;
sendMessage(message: any) {
this.socket.emit('add-message', message);
}
getMessages(): Observable<any> {
return new Observable(observer => {
this.socket = io(this.url, {withCredentials: true});
this.socket.on('message', (data) => {
observer.next(data);
});
return () => {
this.socket.disconnect();
}
})
}
}
4.创建组件
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ChatService } from './chat.service';
@Component({
selector: 'test-chat',
template: `<div *ngFor="let message of messages">
{{message.text}}
</div>
<input [(ngModel)]="message" />
<button (click)="sendMessage()">Send</button>`,
providers: [ChatService] // 注入依赖
})
export class TestChatComponent implements OnInit, OnDestroy {
messages = [];
connection: any;
message: any;
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(); // 组件销毁取消订阅
}
}
如果遇到global is not defined的问题,在polyfills.ts增加一行代码 (window as any).global = window;