Return 个订阅值 (ionic/angular)

Return value from a subscribe (ionic/angular)

所以我想 return 来自订阅的值 :

export class UserHomePage implements OnInit {     
    uid: string;
    ...

constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFireStore,
    ...
) {}

getAuth() {
    return this.afAuth.authState.subscribe(auth => {            <= // It's ok
    this.uid = auth.uid;
    console.log('ID : ' + this.uid);
 });
}

我尝试在其他函数中使用 "this.uid" 但数据是 "undefined" :

example() {                                                     <= // Problem !
    console.log(this.uid);
}

我刚刚在这个论坛上找到了另一个主题,但我不明白可观察的方式。

你能向我解释一下如何 return 这些数据用于下一个功能吗?

谢谢(对不起我的英语)!

我最好的猜测是你的问题是可观察对象是异步的,因此 this.uid returns undefined 如果 example() 在你订阅 [=14] 之前被触发=] returns 任意值。

您可以做的最简单的事情就是从订阅本身调用 example()。这样的事情应该有效:

getAuth() {
  this.afAuth.authState.subscribe(auth => {
    this.uid = auth.uid;
    this.example();
  });
}