[英]web socket connection in angular
我創建了一個 angular 項目,其中我的 web 套接字連接在重新加載頁面后打開,否則它不會打開。 我想在用戶登錄后立即啟動一個套接字,並在它注銷時關閉它。
下面是我使用rxjs
web sockets 而不是socket.io
創建的套接字服務
SOCKET_URL: string = environment.webSocketEndpoint;
ws: WebSocketSubject<any>;
open() {
this.ws = webSocket(`${this.SOCKET_URL}/?access_token=${this.auth.user()?.['accessToken']}&platform=web`);
}
emit(event: Object): void {
this.ws.next(event);
}
events(): Observable<any> {
if (this.ws === undefined ) {
this.open();
}
return this.ws?.asObservable();
}
close() {
this.ws.unsubscribe();
}
}
在app.ts
nogOnit()
上的 app.ts 中:
if(this.auth.user()){
this.socketService.open()}
使用可觀察序列編寫異步和基於事件的程序的庫,非常適合與 WebSockets 一起使用。 簡而言之,RxJS 允許我們偵聽來自 websocket 連接的新消息,然后在發生 'X' 事件時執行操作。 按照這個鏈接看清楚: https : //tutorialedge.net/typescript/angular/angular-websockets-tutorial/# :~: text=WebSockets%20in%20Angular&text= This% 20is%20a%20library%20for,when% 20'X'%20event%20occurs 。
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
import { Subscription } from 'rxjs';
import { Observable } from 'rxjs';
ngOnInit() {
this.WebSocket = webSocket(environment.webSoketBaseURL + '/websocket_path/');
this.webSocket.asObservable().subscribe(response => {
console.log(response)
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.