0

我有一个带有 ng2-stompjs 和 socksjs 客户端和 Spring boot 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 并检查连接状态枚举,但它也不起作用。

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);
}

}

在这一点上,我陷入困境并且没有想法。如果您能提出建议,我将不胜感激!提前致谢。

4

1 回答 1

1

Victor_figm 推荐的方法对我来说非常有效。只听“beforeunload”事件并取消订阅。这就是解决方案:

@HostListener('window:beforeunload', ['$event'])
async onBeforeUnload(): Promise<void> {
  this.unsubscribe();
}
于 2021-09-01T09:19:25.243 回答