angular - Angular 7“未定义”变量
问题描述
是否可以从外部收听订阅者功能?
x:string;
listenertwitchService(){
console.log(this.x);
}
this.twitchService.getUserID(this.Tw_Username).subscribe(data => {
this.x="123";
});
解决方案
这是正常行为:
1)您的 x 未定义
x:字符串;
//should be
x = '';
2) Observables 异步工作,这意味着如果你想使用 x 返回,this.twitchService.getUserID(this.Tw_Username)
你需要使用 rxjs 管道和操作符,因为尝试访问其值被异步设置的全局变量不是一个好主意,因为它很难知道值的 x 将被设置,即当你的 Observable 将被触发时。但是,对于模板绑定,如果您设置了初始值,那么绑定全局变量非常有用,请参见 (1)
this.twitchService.getUserID(this.Tw_Username)
.pipe(tap(data)=>{ //or any other operator ie map/switchMap etc...
//do the thing you want to do to the data
})
.subscribe()
推荐阅读
- go - 在 Go 中为相同的结构类型重新使用相同的编码器/解码器而不创建新的
- azure - Azure Synapse 无服务器 SQL 池 - 查询执行失败
- ansible - Ansible line-in-file 重新添加条目
- imagemagick - 我可以使用 ImageMagick 获取不同颜色像素的数量列表吗?
- hyperledger-fabric - 超级账本结构:总是 MVCC_READ_CONFLICT
- c++ - C++中的“while”命令
- nlp - 如何在 spaCy 中处理很长的文档?
- r - 在数据框中捕获 R 函数的结果、错误和警告
- python-3.x - cPanel Sudo 不可用
- bash - 在 bash 脚本中的文本文件中写入字数