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

时间:2019-06-03 12:29:07

标签: javascript angular typescript 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
    });
  }
}

1 个答案:

答案 0 :(得分:0)

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

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