Angular 将变量设置为异步函数内的值

Angular 将变量设置为异步函数内的值,angular,asynchronous,observable,subscribe,Angular,Asynchronous,Observable,Subscribe,首先,我知道不能这样做,因为不能在异步函数中初始化变量 但我需要你们帮我纠正这一点 在这个例子中,我有一个observable,我想返回它的变量,并在其他函数中使用它 id:string; constructor(){ this.user$.subscribe(data=>{ this.id = data.uid}) console.log(this.id) //undefined } 我知道这是错误的,但我不知道正确的方法 例如,我需

首先,我知道不能这样做,因为不能在异步函数中初始化变量

但我需要你们帮我纠正这一点

在这个例子中,我有一个observable,我想返回它的变量,并在其他函数中使用它

    id:string;
    constructor(){
      this.user$.subscribe(data=>{
      this.id = data.uid})
      console.log(this.id) //undefined
}
我知道这是错误的,但我不知道正确的方法

例如,我需要这里的用户id!但由于它是未定义的,所以我得到了一个错误

 getCat() :Observable<boolean>{
      return this.afs.collection('users').doc(this.id).collection('categories').get().pipe(
        map(data => {
          if(data.size > 0){
            return true
          }else{
            return false
          }
        })
      )
  }
getCat():可观察{
返回此.afs.collection('users').doc(this.id).collection('categories').get().pipe(
地图(数据=>{
如果(data.size>0){
返回真值
}否则{
返回错误
}
})
)
}

对getCat函数的调用应该在用户可观察的订阅中调用,我的意思是在用户id被获取之后

this.user$.subscribe(data=>{

      this.id = data ? data.uid : null;
      console.log(this.id); //should have a value
      this.getCat() // just call the function here 
});

你能分享什么的样本JSON吗?我能看到数据吗?你不是在返回数据,而是
true
false
。返回数据,您将能够访问它的变量。(如果您知道)数据正是facebook的用户对象,因为我使用facebook登录应用程序。它是未定义的,因为您无法初始化异步函数中的变量,但我正在寻找解决方案。实际上,它是未定义的,因为您的响应是未定义的,请通过日志记录控制台重试。log(数据)日志记录对我没有任何作用我需要该值在其他方法中使用它:(pff,我建议您记录,因为this.id为null,因为data为null或data.uid为null。让我修改我的示例。如果我记录数据,它不为null,但this.id始终未定义