Access socket.io on multiple pages


#1

Hi everyone,

I recently added socket.io on my app.

I put the socket.io code in the app.component.ts as you can see here :

 import * as io from "socket.io-client";


declare var cordova: any;

@Component({
  templateUrl: 'app.html'
})

export class MyApp {

rootPage = HomePage;

@ViewChild(Nav) nav;

socket: SocketIOClient.Socket;

//Initialisation de l'application, du fonctionnement de l'application en background et de l'état de le connexion à déconnecté

constructor(platform: Platform, public translate: TranslateService) {

platform.ready().then(() => {

  cordova.plugins.backgroundMode.enable();
  window.localStorage.setItem('connectionState', "disconnected");

   this.socket = io('http://*******');

  this.socket.on('connect', () => {
    console.log("Connexion au serveur de PUSH effectué");
  });

  StatusBar.styleDefault();

  setTimeout(function() {
    Splashscreen.hide();
  }, 100);

});

//Détection automatique de la langue de l'utilisateur, si ni la langue anglaise ni française n'est présente on utilisera la langue anglaise par défaut

var deviceLanguage = 'en';

if(window.navigator.language !== "undefined"){

  if(window.navigator.language.substring(0, 2) == "en" || window.navigator.language.substring(0, 2) == "fr"){

    deviceLanguage = window.navigator.language.substring(0, 2);

  }

}

translate.use(deviceLanguage);

}

But I can’t access through other pages to the socket.io instance, is there a way to “set globally” the socket.io instance to access socket.on / socket.emit function on different pages instead of only app.component.ts

Thanks for the help,
Alvin


#2

Having the same problem keeping the socket object sitting somewhere. Did you ever get this one going?