【问题标题】:I cannot access my variable inside socket.on of socketcluster我无法在 socketcluster 的 socket.on 中访问我的变量
【发布时间】:2019-06-03 12:29:07
【问题描述】:

我想将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
    });
  }
}

【问题讨论】:

    标签: javascript angular typescript socketcluster


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多