【发布时间】:2018-02-15 00:44:51
【问题描述】:
在我的 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() 块中就可以了,因为这应该只在连接的承诺解决后执行,但显然即使没有连接存在(根据错误)它仍然会被触发。
或者还有更多我想念的东西?
【问题讨论】: