Search code examples
javascriptangulartypescriptsocketcluster

I cannot access my variable inside socket.on of socketcluster


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
    });
  }
}

Solution

  • 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;
    });