我无法访问 socketcluster socket.on 内的变量

I cannot access my variable inside socket.on of socketcluster

我想将 msg 的值赋给变量 sample 但它无法在回调中访问 sample

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

this 上下文,几乎可以肯定。我不完全确定在 socket.on 中调用的函数会得到什么 this 上下文,但是箭头函数使用词法 this,所以这将是一个解决方案。

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