0

我想将值分配给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
    });
  }
}
4

1 回答 1

0

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

this.socket.on('random', (msg) => {
  console.log('RANDOM: ' + msg);
  this.sample = msg;
});
于 2019-06-03T12:34:31.650 回答