为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2021-06-11 21:00:47
我想将 的值分配给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 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

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


this.socket.on('random', (msg) => {

  console.log('RANDOM: ' + msg);

  this.sample = msg;

});


查看完整回答
反对 回复 2021-06-18
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信