在Angular項目使用socket.io實現(xiàn)通信的方法
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、編寫后臺服務(wù)
可以在項目中新建一個server文件夾,用來存放我們的后臺服務(wù),然后新建文件
const app = require('express')(); const http = require('http').createServer(app); const io = require('socket.io')(http, { cors: { // 處理跨域問題 origin: "http://localhost:4300", // angular項目的啟動端口,默認(rèn)4200,本人項目的啟動端口為4300,大家根據(jù)自己情況修改 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, () => { // 后臺服務(wù)啟動端口 console.log('start on 4000....'); })
step3、創(chuàng)建angular服務(wù)
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'; // 后臺服務(wù)端口 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(); } }) } }
這里我們創(chuàng)建了兩個方法,sendMessage用于將客戶端的信息發(fā)送給服務(wù)端,getMessages用于建立連接,監(jiān)聽服務(wù)端事件并返回一個可觀察的對象。
step4、創(chuàng)建組件
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通信就完成了,效果圖如下:
啟動服務(wù)
前端頁面
如果遇到跨域問題,大概率是沒有處理跨域,檢查自己的代碼和端口號是否正確,詳情參考handing-cors
另外,如果遇到(本人遇到了,愣是在網(wǎng)上找了半天依然未果)
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';
在網(wǎng)上看到很多人是這樣寫的 import * as io from ‘socket.io-client',這種寫法在typescript中是會報錯的,改成上面的寫法即可。
到此這篇關(guān)于在Angular項目使用socket.io實現(xiàn)通信的文章就介紹到這了,更多相關(guān)Angular使用socket.io實現(xiàn)通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
分享Angular http interceptors 攔截器使用(推薦)
AngularJS 是一個 JavaScript 框架。它可通過 <script> 標(biāo)簽添加到 HTML 頁面。這篇文章主要介紹了分享Angular http interceptors 攔截器使用(推薦),需要的朋友可以參考下2019-11-11初學(xué)者AngularJS的環(huán)境搭建過程
這篇文章主要介紹了初學(xué)者AngularJS的環(huán)境搭建過程,在文章給大家提到了Angular-cli的特性,大家一起看看吧2017-10-10angularJs中orderBy篩選以及filter過濾數(shù)據(jù)的方法
今天小編就為大家分享一篇angularJs中orderBy篩選以及filter過濾數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09詳解angularjs popup-table 彈出框表格指令
本篇文章主要介紹了angularjs popup-table 彈出框表格指令,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09