在Angular項(xiàng)目使用socket.io實(shí)現(xiàn)通信的方法
step1、為項(xiàng)目安裝依賴
在終端輸入以下命令為我們的angular項(xiàng)目安裝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、編寫(xiě)后臺(tái)服務(wù)
可以在項(xiàng)目中新建一個(gè)server文件夾,用來(lái)存放我們的后臺(tái)服務(wù),然后新建文件
const app = require('express')(); const http = require('http').createServer(app); const io = require('socket.io')(http, { cors: { // 處理跨域問(wèn)題 origin: "http://localhost:4300", // angular項(xiàng)目的啟動(dòng)端口,默認(rèn)4200,本人項(xiàng)目的啟動(dòng)端口為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, () => { // 后臺(tái)服務(wù)啟動(dòng)端口 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'; // 后臺(tái)服務(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)建了兩個(gè)方法,sendMessage用于將客戶端的信息發(fā)送給服務(wù)端,getMessages用于建立連接,監(jiān)聽(tīng)服務(wù)端事件并返回一個(gè)可觀察的對(duì)象。
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 => { // 組件初始化時(shí)訂閱信息 this.messages.push(message); }); } ngOnDestroy() { this.connection.unsubscribe(); // 組件銷(xiāo)毀取消訂閱 } }
這樣一個(gè)簡(jiǎn)單的socket通信就完成了,效果圖如下:
啟動(dòng)服務(wù)
前端頁(yè)面
如果遇到跨域問(wèn)題,大概率是沒(méi)有處理跨域,檢查自己的代碼和端口號(hào)是否正確,詳情參考handing-cors
另外,如果遇到(本人遇到了,愣是在網(wǎng)上找了半天依然未果)
POST http://localhost:4000/socket.io/?EIO=3&transport=polling&t=NQtz_E3 400 (Bad Request)
這類(lèi)的報(bào)錯(cuò),npm安裝socket.io-client(這也是為什么我在文章一開(kāi)始就安裝它),在service.ts文件引入
import { io } from 'socket.io-client';
在網(wǎng)上看到很多人是這樣寫(xiě)的 import * as io from ‘socket.io-client',這種寫(xiě)法在typescript中是會(huì)報(bào)錯(cuò)的,改成上面的寫(xiě)法即可。
到此這篇關(guān)于在Angular項(xiàng)目使用socket.io實(shí)現(xiàn)通信的文章就介紹到這了,更多相關(guān)Angular使用socket.io實(shí)現(xiàn)通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
AngularJS基礎(chǔ)知識(shí)筆記之過(guò)濾器
在我們開(kāi)發(fā)中經(jīng)常需要在頁(yè)面顯示給用戶的信息需要一定處理格式化,才能顯示給用戶。比如時(shí)間本地化,或者yyyy-MM-dd HH:mm:ss格式,數(shù)字精度格式化,本地化,人名格式化等等。在angularjs中為我們提供了叫filter的指令,讓我們能夠很輕易就能做到著一些列的功能2015-05-05分享Angular http interceptors 攔截器使用(推薦)
AngularJS 是一個(gè) JavaScript 框架。它可通過(guò) <script> 標(biāo)簽添加到 HTML 頁(yè)面。這篇文章主要介紹了分享Angular http interceptors 攔截器使用(推薦),需要的朋友可以參考下2019-11-11初學(xué)者AngularJS的環(huán)境搭建過(guò)程
這篇文章主要介紹了初學(xué)者AngularJS的環(huán)境搭建過(guò)程,在文章給大家提到了Angular-cli的特性,大家一起看看吧2017-10-10angularJs中orderBy篩選以及filter過(guò)濾數(shù)據(jù)的方法
今天小編就為大家分享一篇angularJs中orderBy篩選以及filter過(guò)濾數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09詳解angularjs popup-table 彈出框表格指令
本篇文章主要介紹了angularjs popup-table 彈出框表格指令,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09