从订阅(离子角)返回值

问题描述 投票:0回答:1

所以我想从一个订阅中返回一个值。

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);
}

我只是在这个论坛上找到了另一个主题 此处 但我不明白观察的方式。

能否向我解释一下如何为下一个函数返回这些数据。

谢谢(对不起,我的英语)!我想从一个订阅中返回一个值

angular ionic-framework return observable subscribe
1个回答
0
投票

我最好的猜测是,你这里的问题是观测值是异步的,因此,你的问题是 this.uid 返回 undefined 如果 example() 是在您订购之前触发的。this.afAuth.authState 返回任何值。

最简单的做法是调用 example() 从订阅本身。类似这样的东西应该可以用。

getAuth() {
  this.afAuth.authState.subscribe(auth => {
    this.uid = auth.uid;
    this.example();
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.