Issue
When using stomp.js and sockjs from within Javascript, I can connect well with a Spring Boot backend.
When using stompjs and sockjs from with Angular5, I keep on getting these errors:
InvalidStateError: The connection has not been established yet
Is there a workaround? Just adding the sockjs.min.js, as mentioned in this post, was not helping.
The detailed log is:
Setting up connection/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 Setting up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 Going to subscribe ... main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web Socket... main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> SEND destination:/app/chat.addUser content-length:29
{"sender":"me","type":"JOIN"} main.3388a5e3a20e64e3bdb8.bundle.js:1 ERROR Error: Uncaught (in promise): Error: InvalidStateError: The connection has not been established yet Error: InvalidStateError: The connection has not been established yet at r.send (scripts.d6f701ecf84f24372966.bundle.js:1)
My code in Angular (translated from Javascript) is:
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
console.log('Setting up connection/2');
console.log('Going to subscribe ... ');
this.stompClient.connect({}, function (frame) {
console.log('Going to subscribe ... ');
that.stompClient.subscribe('/topic/public', (payload) => {
console.log('Subscribe: Incoming message: ' + payload.body);
if (payload.body) {
let message = JSON.parse(payload.body);
if (message.sender === 'MyBot') {
this.createAndAddChat('you', message.content);
} else {
this.createAndAddChat('me', message.content);
}
console.log('New message arrived: ' + payload.body);
}
},
error => {
console.log( 'Subscribe: error: ' + error)
},
() => {
console.log( 'Subscribe, On complete')
});
});
this.stompClient.send("/app/chat.addUser", {},
JSON.stringify({sender: 'me', type: 'JOIN'})
)
Solution
The send method is now called directly after starting (!) the asynchronous get-connection call. That's wrong.
There are 2 solutions:
- Good: Put the send call within the async-body of the get-connection. So after the connection is made, call the send method.
- Not optimal: Wait for some time to have the async get-connection to complete.
Answered By - tm1701
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.