猿问

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

我想将 的值分配给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

    });

  }

}


心有法竹
浏览 118回答 1
1回答

繁星coding

this上下文,几乎可以肯定。我不完全确定this在socket.onget内部调用的函数将使用什么上下文,但箭头函数使用 lexical this,因此这将是一种解决方案。this.socket.on('random', (msg) => {&nbsp; console.log('RANDOM: ' + msg);&nbsp; this.sample = msg;});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答