当tab关闭时关闭Websocket连接



我有一个带有ng2-stompjs和socksjs客户端和Spring启动Websocket服务器的Angular。我想做的是,当当前浏览器选项卡关闭时断开与Websocket的连接。

@Component({
selector: 'app-test-list',
templateUrl: './test-list.component.html',
styleUrls: ['./test-list.component.css']
})
export class TestListComponent implements OnInit, OnDestroy {
// Stream of messages
private subscription: Subscription;
public messages: Observable<Message>;
// Subscription status
public subscribed: boolean;
// Array of historic message (bodies)
public mq: Array<string> = [];
// A count of messages received
public count = 0;
private _counter = 1;

constructor(private _stompService: StompService) {
}
sendMessage() {
this._stompService.publish('/app/hello', 'My important message');
}

尝试断开'OnDestroy',但没有帮助

ngOnDestroy(): void {
this.sendMessage();
this.unsubscribe()
}

尝试订阅connectionState并检查连接状态enum,但也不工作。

ngOnInit(): void {
this.subscribed = false
this.subscribe();
this._stompService.connectionState$.subscribe(next => {
console.log('Connection State', RxStompState[next]);
if(next === RxStompState.CLOSING) {
this.unsubscribe()
}
});
}

public subscribe() {
if (this.subscribed) {
return;
}
// Stream of messages
this.messages = this._stompService.subscribe('/topic/hi');
// Subscribe a function to be run on_next message
this.subscription = this.messages.subscribe(this.on_next);
this.subscribed = true;
}

public unsubscribe() {
if (!this.subscribed) {
return;
}
// This will internally unsubscribe from Stomp Broker
// There are two subscriptions - one created explicitly, the other created in the 
template by use of 'async'
this.subscription.unsubscribe();
// this._stompService.disconnect();
this.subscription = null;
this.messages = null;
this.subscribed = false;
}

public onSendMessage() {
const _getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
this._stompService.publish('/topic/ng-demo-sub',
`{ type: "Test Message", data: [ ${this._counter}, ${_getRandomInt(1, 100)}, 
${_getRandomInt(1, 100)}] }`);
this._counter++;
}

/** Consume a message from the _stompService */
public on_next = (message: Message) => {
// Store message in "historic messages" queue
this.mq.push(message.body + 'n');
// Count it
this.count++;
// Log it to the console
console.log(message);
}
}
在这一点上,我被困住了,没有主意了。如果你能给我一些建议,我将不胜感激!提前谢谢。

Victor_figm推荐的方法对我来说效果很好。只是听'beforeunload'事件和取消订阅。这就是解决方案:

@HostListener('window:beforeunload', ['$event'])
async onBeforeUnload(): Promise<void> {
this.unsubscribe();
}

最新更新