angular - 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;
});
}
解决方案
您可以从简单函数更改为箭头函数。然后this
仍然引用您的课程。
this.socket.on('catvotes', (catData) => {
console.log(catData);
this.catVotes = catData;
});
但也请查看 JB 提供的链接,因为它提供了功能更全面的答案,并详细讨论了主题和选项。
推荐阅读
- java - 运行覆盖产生的测试:本机方法中的致命错误:-javaagent 处理失败
- database - 如何仅使用上一个查询生成的搜索集在 ElasticSearch 中搜索当前查询
- java - 使用背景不透明度值的 Fading CurveVertex() 轨迹不起作用
- django - Django group by 和 count(*),包括零计数
- python-3.x - 如何为 Windows 10 上的所有用户安装 Python3 和带有 Miniconda3 的库?
- google-analytics - 自定义维度中的 ga 到 gtag 结合自定义报告和虚拟综合浏览量
- terraform - Terraform 无法识别 authenticate-oidc 类型
- python - 如何修复 LDAPSocketReceiveError:接收数据时出错:使用 LDAP_MATCHING_RULE_IN_CHAIN/1.2.840.113556.1.4.1941 时读取操作超时?
- c++ - 列表
> 遍历包含对的列表? - html - Angular Material => 从 formControlName 中设置 mat-select 的值