首页 > 解决方案 > ngOnInit scope with this

问题描述

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;
    });

  }

标签: angular

解决方案


您可以从简单函数更改为箭头函数。然后this仍然引用您的课程。

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

但也请查看 JB 提供的链接,因为它提供了功能更全面的答案,并详细讨论了主题和选项。


推荐阅读