I have an Ionic3 app that on a certain view, connect on view enter and subscribe to a websocket observable/observer service:
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);
}
Then, when leaving view, unsubscribe:
ionViewWillLeave() {
this.socket.message.next(this.quitMessage);
this.subscribtion.unsubscribe();
}
But if I reenter the view, It will not reconnect to the websocket. How should I do it?
Here 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);
}
}
from How reconnect (resubscribe) to websocket on typescript
No comments:
Post a Comment