我想将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
});
}
}发布于 2019-06-03 20:34:32
this上下文,几乎可以肯定。我不能完全确定在socket.on get中调用的函数的this上下文是什么,但是箭头函数使用词法this,所以这是一种解决方案。
this.socket.on('random', (msg) => {
console.log('RANDOM: ' + msg);
this.sample = msg;
});https://stackoverflow.com/questions/56427407
复制相似问题