我在Angular中使用RXJS,并且有一个websocket服务,该服务是RXJS WebSocketSubject的简单包装。
我还有一些服务需要订阅此服务以获取数据。在这些服务启动时,他们订阅了“基本” websocket。
这可以正常工作,直到基本的websocket断开与服务器的连接。它可以正确地重新建立自身,因此我可以将数据推送到服务器。但是,我的其他服务所拥有的订阅没有得到重新应用,因此我无法接收任何数据。
解决此问题的推荐方法是什么?谢谢!
基本websocket(简体):
function filtered_range(start, end, banned) {
let nums = [];
for (let i = start; i <= end; i++) {
if (i % banned != 0 && i.toString().indexOf(banned) == -1) nums.push(i);
}
return nums;
}
console.log(filtered_range(1, 90, 8).join(' '));
使用基本websocket的示例服务(简体):
import { Injectable } from '@angular/core';
import { WebSocketSubject, WebSocketSubjectConfig } from 'rxjs/webSocket';
import { AuthService } from './auth-service';
import { UrlService } from './url-service';
@Injectable({
providedIn: 'root'
})
export class AppWsService {
private socket!: WebSocketSubject<any>;
constructor(private urlService: UrlService) {
this.initialize();
}
private async initialize() {
await this.fetchWebsocket();
}
private async send_message(message: any) {
await this.fetchWebsocket();
console.log('[BASE] Send message', message);
this.socket.next(message);
}
public async fetchWebsocket(): Promise<WebSocketSubject<any>> {
if (!this.socket) {
let config: WebSocketSubjectConfig<any> = {
url: this.urlService.get_ws_url(),
openObserver: {
next: (_: any) => {
let msg = {
// Include auth stuff here
};
this.socket.next(msg as any);
},
error: (err: any) => {
console.log('[BASE][WS] Error connecting:', err);
}
}
};
console.log('[BASE][WS]Making subject...')
this.socket = new WebSocketSubject(config);
this.socket.subscribe({
next: (data) => {
console.debug('[BASE][WS] Got message:', data);
console.debug('[BASE][WS] Type:', data.constructor.name);
},
error: (msg) => {
console.error('[BASE][WS] Error:', msg);
}
});
}
console.log('[BASE][WS] Returning subject')
return this.socket;
}
}