Reputation: 8855
I am using the angular2-websocket wrapper. Although I have not closed the websocket, when I attempt to send a message later, I get an error saying that the websocket has already been closed.
My component looks like the following.
export class ListDataComponent implements OnInit, OnDestroy, AfterViewInit {
ws: $WebSocket;
sub: Subscription;
ngAfterViewInit() { this.initWebSocket(); }
ngOnDestroy() { this.destroyWebSocket(); }
initWebSocket(): void {
this.ws = new $WebSocket('ws://localhost:8080/topic/data');
this.sub = this.ws.getDataStream().subscribe(
data => {
console.log(data);
//this part is following the example on the github page
//makes me unsure because the close method will force a close and true/false only signifies if the closing is immediate or not
//even if i comment out this line, i still get the same behavior
this.ws.close(false);
},
err => console.err(data)
);
}
destroyWebSocket(): void {
//this is the only place where i destroy/release my websocket resources
if (this.sub) {
try {
this.sub.unsubscribe();
} catch(err) { }
}
if (this.ws) {
try {
this.ws.close(true);
} catch(err) { }
}
}
//this method is bound to a bunch of checkboxes that triggers sending data back to the websocket topic
selectionChanged(i: number): void {
let json = getSomeJson(i); //gets some JSON to send back; omitted
this.ws.send(json).subscribe(
data => console.log(data),
err => {
//it seems i can't send because the websocket has been closed! why?
console.error(err);
}
);
}
}
Looking at the JavaScript console, I see the following message.
Socket connection has been closed (anonymous) @ list-data-ws.component.ts:141 SafeSubscriber.__tryOrSetError @ Subscriber.js:243 SafeSubscriber.error @ Subscriber.js:199 Subscriber._error @ Subscriber.js:128 Subscriber.error @ Subscriber.js:102 (anonymous) @ angular2-websocket.js:123 Observable._trySubscribe @ Observable.js:57 Observable.subscribe @ Observable.js:45 webpackJsonp.362.ListTransactionWsComponent.cryptoSelected @ list-transaction-ws.component.ts:139 View_ListTransactionWsComponent1.handleEvent_2 @ /AppModule/ListTransactionWsComponent/component.ngfactory.js:68 (anonymous) @ view.js:664 (anonymous) @ dom_renderer.js:489 webpackJsonp.946.ZoneDelegate.invokeTask @ zone.js:363 onInvokeTask @ ng_zone.js:264 webpackJsonp.946.ZoneDelegate.invokeTask @ zone.js:362 webpackJsonp.946.Zone.runTask @ zone.js:166 ZoneTask.invoke
What's weird is that I still keep getting data coming back in the data stream. I have also placed debugging messages on the backend (Spring Boot) and I don't see that the websocket has been closed.
If it helps,
Upvotes: 0
Views: 875
Reputation: 8855
I was using 0.9.0 of angular2-websocket. After upgrading to 0.9.1, everything works as expected. Hope this information helps anyone else out there: DO NOT USE v0.9.0.
Upvotes: 1