我想将 的值分配给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;
});
添加回答
举报
0/150
提交
取消