0

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
    });
  }
}
kalehmann
  • 4,821
  • 6
  • 26
  • 36
Clyde Santos
  • 305
  • 2
  • 6

1 Answers1

0

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;
});
mbojko
  • 13,503
  • 1
  • 16
  • 26