I cannot access my variable inside socket.on of socketcluster

147 Views Asked by At

I want to assign the value of msg to the variable sample but it cannot access sample inside the callback.

import { Injectable } from '@angular/core';

import * as socketCluster from 'socketcluster-client';

@Injectable({
  providedIn: 'root'
})


export class DatamanagerService {

  socket = socketCluster.create({
    port: 8000
  });

  sample:string;

  constructor() { 

  }

  connect() {
    this.socket.on('connect', function () {
      console.log('CONNECTED');
    });

    this.socket.on('random', function (msg) {
      console.log('RANDOM: ' + msg);
      this.sample = msg; // <- here
    });
  }
}
1

There are 1 best solutions below

0
mbojko On BEST ANSWER

this context, almost certainly. I'm not entirely certain what this context will a function called inside socket.on get, but arrow functions use the lexical this, so that would be one solution.

this.socket.on('random', (msg) => {
  console.log('RANDOM: ' + msg);
  this.sample = msg;
});