在Angular專案使用socket.io實現通訊
阿新 • • 發佈:2021-01-08
技術標籤:angularsockettypescriptangularnode.js
step1、為專案安裝依賴
在終端輸入以下命令為我們的angular專案安裝express、socket.io、socket.io-client
npm install express socket.io socket.io-client
本人安裝的各版本資訊如下:
"express": "^4.17.1", "socket.io": "^3.0.4", "socket.io-client": "^3.0.4",
step2、編寫後臺服務
可以在專案中新建一個server資料夾,用來存放我們的後臺服務,然後新建檔案
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....' );
})
step3、建立angular服務
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { 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();
}
})
}
}
這裡我們建立了兩個方法,sendMessage用於將客戶端的資訊傳送給服務端,getMessages用於建立連線,監聽服務端事件並返回一個可觀察的物件。
step4、建立元件
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(); // 元件銷燬取消訂閱
}
}
這樣一個簡單的socket通訊就完成了,效果圖如下:
啟動服務
前端頁面
如果遇到跨域問題,大概率是沒有處理跨域,檢查自己的程式碼和埠號是否正確,詳情參考handing-cors
另外,如果遇到(本人遇到了,愣是在網上找了半天依然未果)
POST http://localhost:4000/socket.io/?EIO=3&transport=polling&t=NQtz_E3 400 (Bad Request)
這類的報錯,npm安裝socket.io-client(這也是為什麼我在文章一開始就安裝它),在service.ts檔案引入
import { io } from 'socket.io-client';
在網上看到很多人是這樣寫的 import * as io from ‘socket.io-client’,這種寫法在typescript中是會報錯的,改成上面的寫法即可。
2021年第一篇文章!2021繼續加油!如果本文章對你有幫助就點個贊吧>o<!(沒有幫助也可給個