'How to maintain a Websocket connection for my Angular(13.0.4) application across pages? I need to load the websocket url into service not at the start
So this is my web-socket.service.ts where I send the url information to the websocket in order to establish the connection:
import { Injectable } from '@angular/core';
import { Observable, Observer, Subject } from 'rxjs';
import { AnonymousSubject } from 'rxjs/internal/Subject';
import { Message } from './ws-message.type'
import { Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
private subject: AnonymousSubject<MessageEvent>;
public messages: Subject<Message>;
private jwt: string;
constructor(private router: Router) {
}
public connect(url): AnonymousSubject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): AnonymousSubject<MessageEvent> {
let ws = new WebSocket(url);
let observable = new Observable((obs: 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 = {
error: null,
complete: null,
next: (data: Object) => {
console.log('Message sent to websocket: ', data);
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
};
return new AnonymousSubject<MessageEvent>(observer, observable);
}
}
Currently I make the connection on my typescript by:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { webSocket } from 'rxjs/webSocket';
import { MenuController } from '@ionic/angular';
@Component({
selector: 'app-org',
templateUrl: './org.page.html',
styleUrls: ['./org.page.scss'],
})
export class OrgPage implements OnInit {
jwt: string;
ws_session;
stringObject: any;
stringJson: any;
content:any = [];
constructor(public menuCtrl: MenuController, private router: Router) {
this.jwt = sessionStorage.getItem("jwt");
if (this.jwt) {
this.ws_session = webSocket(environment.WS_API_URL + '/connect/' + this.jwt);
this.ws_session.subscribe(msg => {
if (msg.action == "get_my_orgs"){
this.content = Object.assign(msg.content);
this.stringJson = JSON.stringify(this.content);
this.stringObject = JSON.parse(this.stringJson);
console.log("JSON object -", this.stringObject);
}
});
}
}
The connection currently works, but I create a new connection every page. I only want one connection across all pages as soon as I make the call to establish the connection. I'd like to know how to close the connection as well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
