我有三頁。主頁、聊天頁面和帶有聊天圖示的頂部導航頁面。當用戶收到新訊息時,我想在頂部導航中顯示帶有聊天圖示的徽章。為此,我在聊天模型中維護了一個名為 see 的標志。這是一個布林值。如果 seen 為false,我將計算錯誤的記錄數并在帶有聊天圖示的徽章中顯示計數。為此,我在頂部導航ngOnit() 中撰寫了一個方法來檢查聊天模型是否有任何看不見的訊息。我覺得它會影響性能,因為如果每隔一秒點擊一次 API。有沒有比setInterval更好的方法。
頂部導航 TS
ngOnInit()
{
setInterval(() => {
//API Call
}, 1000);
}
uj5u.com熱心網友回復:
您應該考慮建立一個websocket服務器,而不是不斷地訪問 API 。您可以從Angular應用程式連接到您的服務器emit并listen實時發送訊息。
服務器(NodeJs 上的 websocket)
這是一個簡單的websocket服務器的樣子NodeJs:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8081 });
wss.on('connection', ws => {
onConnection(ws);
ws.on('message', message => {
onMessage(message, ws);
});
ws.on('error', error => {
OnError(error);
});
ws.on('close', ws=> {
onClose();
})
});
客戶端(角度)
在您的 Angular 應用程式中,這就是處理此連接的客戶端服務的樣子。本質上,您創建了一個連接到您的服務器、處理emit和subscriptions發送新訊息到Subject. 您可以將其Subject作為Observable然后在您的組件中訂閱它的方式回傳。
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { environment } from '../../environments/environment';
import { catchError, tap, switchAll } from 'rxjs/operators';
import { EMPTY, Subject } from 'rxjs';
export const WS_ENDPOINT = environment.wsEndpoint;
@Injectable({
providedIn: 'root'
})
export class DataService {
private socket$: WebSocketSubject<any>;
private messagesSubject$ = new Subject();
public messages$ = this.messagesSubject$.pipe(switchAll(), catchError(e => { throw e }));
public connect(): void {
if (!this.socket$ || this.socket$.closed) {
this.socket$ = this.getNewWebSocket();
const messages = this.socket$.pipe(
tap({
error: error => console.log(error),
}), catchError(_ => EMPTY));
this.messagesSubject$.next(messages);
}
}
private getNewWebSocket() {
return webSocket(WS_ENDPOINT);
}
sendMessage(msg: any) {
this.socket$.next(msg);
}
close() {
this.socket$.complete(); }}
看看這篇文章,它描述了websocket服務器的作業以及來自Angular應用程式的連接:https : //javascript-conference.com/blog/real-time-in-angular-a-journey-into-websocket-and -rxjs/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385815.html
標籤:javascript 有角的 打字稿 休息
下一篇:啟動時創建sqlite資料庫一次
