Real Chat using Ionic + Socket.io - Problem to get data outside socket.on function

Hello everybody,

I’m developing a real chat application on Ionic and i have some problems to access data outside the socket.on(…) 's function when an user send a message.

Here is my program :

salon-chat.component

export class SalonChatPage{
  currentUser: User;

  constructor(public navCtrl: NavController, private navParams: NavParams, public menuCtrl:   MenuController, private chatService: ChatService) {
    this.menuCtrl.enable(true, 'chat');
    this.menuCtrl.enable(false, 'home');

    this.currentUser = this.navParams.get('user');
    this.chatService.logServer(this.currentUser);
  }

  send(message){
    let newmsg = this.chatService.sendMessage(message.value);
    console.log(newmsg); // NOT OK
  }
}

chat-service

@Injectable()
export class ChatService {
    private socketHost: string = "http://localhost:3000/";
    private socket: any;
    private message:string;

    constructor() {

    }

    logServer(user: User) {
        this.socket = io.connect(this.socketHost);
        this.socket.emit('login', user);
    }

    sendMessage(msg: string) {
        this.socket.emit('message', msg);
        console.log("send message: " + msg);
        this.socket.on('newmsg', (newmsg) => {
           this.message = newmsg;
           console.log("client message received: " + this.message); // OK
        });

        console.log(this.message); // NOT OK
        return this.message;
    }
}

server.js

var io = require('socket.io'),
    http = require('http'),
    server = http.createServer(),
    io = io.listen(server);

var messages = [];

io.on('connection', function(socket) {
    console.log('User Connected');
    socket.on('login', function(user){
        console.log(user);
    });

    socket.on('message', function (message) {
        socket.emit('newmsg', message);
    })
});

server.listen(3000, function(){
    console.log('Server started');
});

How can i get the value and returned it to my component ?

Thanks in advance

You could use observables...something like

In your chat-service:


private newMessageSource: Subject<String> = new Subject<String>();
newMessage: Observable<String> = this.newMessageSource.asObservable();

constructor() {

}

sendMessage(msg: string) {
       this.socket.on('newmsg', (newmsg) => {
            this.message = newmsg;
            this.newMessageSource.next(newmsg);
        }
  }

and in your component:

   private newMessageSubscription: Subscription;

  ionViewDidEnter() {
     this.newMessageSubscription = this.chatService.newMessage.subscribe((newMessage:String) => {
    console.log("client message received: " + newMessage);
 }
 
 ionViewWillLeave() {
    if (this.newMessageSubscription != null) {
        this.newMessageSubscription.unsubscribe();
    }
 }