rxjs: rxjs/webSocket SyntaxError: Unexpected token s in JSON at position 0
Bug Report
Current Behavior
using string urlConfigOrSource
generates SyntaxError: Unexpected token s in JSON at position 0
with WebSocketSubjectConfig
and defined deserializer
function error does not appear.
Reproduction
this.pubsubSubject = webSocket('ws://localhost:8080');
this.pubsubSubject.subscribe(
(msg) => console.log('message received: ' + msg),
(err) => console.log(err),
() => console.log('complete')
);
throws error
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse (<anonymous>)
at deserializer (WebSocketSubject.js:12)
at tryCatcher (tryCatch.js:6)
at WebSocket.socket.onmessage [as __zone_symbol__ON_PROPERTYmessage] (WebSocketSubject.js:174)
at WebSocket.wrapFn (zone.js:1188)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3811)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:496)
to fix this we need use:
this.pubsubSubject = webSocket({
url: 'ws://localhost:8080',
deserializer: () => {}
});
after that this.pubsubSubjectsubscribe()
doesn’t throw error
Environment
- Runtime: @angular 6.1.8 chrome 69.0.3497.100
- RxJS version: 6.3.2
- angular-cli 6.2.3,
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 1
- Comments: 16 (10 by maintainers)
By default webSocketSubject is trying to deserialize the message by applying
JSON.parse()
. If you message is not an string is going to fail (the error you are getting now). Now when you tell towebSocket
to use this deserializer() => {}
, you are telling it, just give me back anundefined
value (Since it is returning nothing).Here you have two options,
Example: Here you can apply whatever transformation you want. I just not applying anything but avoiding the default behaviour (
JSON.parse()
). SinceJSON.parse()
attempts to transform an string to a JSON object and surely you are not expecting that type of data (an string coming from your server).This seems like it was just a debugging session. Closing.
@luillyfe it works in this way, thanks.