我创建了一个angular项目,其中我的web套接字连接在重新加载页面后打开,否则它不会打开。我想在用户登录时立即启动套接字,并在用户注销时关闭套接字。
下面是我使用rxjs
而不是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();
}
}
Inapp.ts
onnogOnit()
:
if(this.auth.user()){
this.socketService.open()}
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)
});
}