是否可以从外部收听订户功能?
x:string;
listenertwitchService(){
console.log(this.x);
}
this.twitchService.getUserID(this.Tw_Username).subscribe(data => {
this.x="123";
});
答案 0 :(得分:0)
这是正常现象:
1)您的x未定义
x:string;
//should be
x = '';
2)Observables异步工作,这意味着如果要使用this.twitchService.getUserID(this.Tw_Username)
的x return,则需要使用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()
答案 1 :(得分:0)
如果您在console.log(this.x)
之后subscribe
仍未定义,因为subscribe
调用asynchronous
,它将不会等待从getUserID
返回数据并运行下一行代码
this.twitchService.getUserID(this.Tw_Username)
.subscribe(data => {
this.x="123";
});
//still undefined
console.log(this.x)