[英]web socket connection in angular
I have created a angular project in which my web socket connection is getting open after reloading the page otherwise it does not open.我创建了一个 angular 项目,其中我的 web 套接字连接在重新加载页面后打开,否则它不会打开。 I want to start a socket as soon as user logs in and close the socket as it logs out.
我想在用户登录后立即启动一个套接字,并在它注销时关闭它。
Below is the socket service I created using rxjs
web sockets not socket.io
:下面是我使用
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();
}
}
In app.ts
on nogOnit()
:在
app.ts
nogOnit()
上的 app.ts 中:
if(this.auth.user()){
this.socketService.open()}
library for composing asynchronous and event-based programs using observable sequences and is perfect for working with WebSockets.使用可观察序列编写异步和基于事件的程序的库,非常适合与 WebSockets 一起使用。 Simply put, RxJS allows us to listen to new messages from a websocket connection and then perform an action when 'X' event occurs.
简而言之,RxJS 允许我们侦听来自 websocket 连接的新消息,然后在发生 'X' 事件时执行操作。 Follow this link to understand it clearly: https://tutorialedge.net/typescript/angular/angular-websockets-tutorial/#:~:text=WebSockets%20in%20Angular&text=This%20is%20a%20library%20for,when%20'X'%20event%20occurs .
按照这个链接看清楚: 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.