In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view:
subscribtion: Subscription;
ionViewDidEnter() {
this.subscribtion = this.socket.message.subscribe(msg => {
let configs = <Configs>msg.data
this.inputs = configs.inputs;
});
this.socket.message.next(this.enterMessage);
}
When leaving the view, I unsubscribe from the websocket:
ionViewWillLeave() {
this.socket.message.next(this.quitMessage);
this.subscribtion.unsubscribe();
}
The issue arises when reentering the view, as it does not reconnect to the websocket. How can I resolve this?
Below are the details of the socket and websocket.ts :
@Injectable()
export class SocketProvider {
public message: Subject<Message>;
constructor(private socket: WebsocketProvider, @Inject('server') private server) {
console.log('Hello SocketProvider Provider');
let wsAddr = this.server.webSocketUrl();
this.message = <Subject<Message>>socket
.connect(wsAddr)
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return data;
})
}
}
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
//console.log('successfully Connnect: ' + url);
}
return this.subject;
}
public create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
}
)
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}