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
});
}
}
thiscontext, almost certainly. I'm not entirely certain whatthiscontext will a function called insidesocket.onget, but arrow functions use the lexicalthis, so that would be one solution.