首页 > 解决方案 > Angular 7“未定义”变量

问题描述

是否可以从外部收听订阅者功能?

x:string;
listenertwitchService(){
     console.log(this.x);
}

this.twitchService.getUserID(this.Tw_Username).subscribe(data => {
     this.x="123";
});

标签: angularangular7

解决方案


这是正常行为:

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()

欲了解更多信息:https ://www.learnrxjs.io/operators/


推荐阅读