在我的Angular 2项目中,我使用ng2-stomp-service建立与服务器的套接字连接。
大部分时间它工作正常,但有时我在尝试订阅套接字时遇到此错误,说我的连接尚未建立:
Error: Uncaught (in promise): Error: InvalidStateError: The connection has not been established yet Error: InvalidStateError: The connection has not been established yet
at SockJS.send (main.js:158)
at Client._transmit (stomp.js:159)
at Client.subscribe (stomp.js:379)
at StompService.subscribe (stomp.service.ts:132)
at slide-manager.service.ts:129
at ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.es5.js:3933)
at ZoneDelegate.invoke (zone.js:390)
at Zone.run (zone.js:141)
at zone.js:818
at SockJS.send (main.js:158)
at Client._transmit (stomp.js:159)
at Client.subscribe (stomp.js:379)
at StompService.subscribe (stomp.service.ts:132)
at slide-manager.service.ts:129
at ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.es5.js:3933)
at ZoneDelegate.invoke (zone.js:390)
at Zone.run (zone.js:141)
at zone.js:818
at resolvePromise (zone.js:770)
at zone.js:821
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3924)
at ZoneDelegate.invokeTask (zone.js:423)
at Zone.runTask (zone.js:191)
at drainMicroTaskQueue (zone.js:584)
at WebSocket.ZoneTask.invoke (zone.js:490)
属于我的这个堆栈跟踪的一部分是slide-manager.service.ts:129。该代码位于此代码的stomp.subscribe行:
this.socketConfig = {
host: 'http://' + getHost() + '/app-ws',
debug: true,
queue: {'init': false}
};
this.stomp.configure(this.socketConfig);
this.stomp.startConnect().then((frame) => {
this.stomp.done('init');
this.connected = true;
this.spectraSubscription = this.stomp.subscribe('/topic/spectra', (spectra) => {
if (spectra && (!this.theChart || hostElement.childElementCount === 0) && !this.refreshFlag) {
this.makeChart(spectra.points, hostElement);
this.refreshFlag = true;
} else if (spectra && (this.theChart || hostElement.childElementCount > 0) || this.refreshFlag) {
this.theChart.collectionView.sourceCollection = spectra.points;
this.theChart.collectionView.refresh();
}
});
如何在尝试执行.subscribe()之前确保连接确实已建立?我想把它放在.then()块就可以了,因为这只应该在连接的承诺解决后执行,但显然即使没有连接也会被触发(根据错误)。
或者我在这里玩的还有更多吗?
答案 0 :(得分:3)
我可以通过检查stomp客户端的内置“status”属性来解决此问题:
if (this.stomp.status === 'CONNECTED') {
// do stuff that requires a connection, like establish subscriptions
}