1

I have this scope problem. I understand that the lines "this.catVotes = catData" is inside another function so I can't send it directly to "catVotes: Number;"

How can I solve this?

catVotes: Number;
dogVotes: Number;

  constructor(private votingService: VotingService, private socket: Socket) { }

  ngOnInit() {

    this.socket.on('catvotes', function(catData){
      console.log(catData);
      this.catVotes = catData;
    });

    this.socket.on('dogvotes', function(dogData){
      console.log(dogData);
      this.dogVotes = dogData;
    });

  }
eixcs
  • 1,957
  • 4
  • 15
  • 37

1 Answers1

0

You can change from a simple function to an arrow function. Then this remains referencing your class.

this.socket.on('catvotes', (catData) => {
  console.log(catData);
  this.catVotes = catData;
});

But also check out the link provided by JB as it provides a much more full-featured answer with a detailed discussion of the topic and options.

DeborahK
  • 57,520
  • 12
  • 104
  • 129