【问题标题】:Return value from a subscribe (ionic/angular)订阅的返回值(离子/角度)
【发布时间】:2020-04-26 19:47:28
【问题描述】:

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

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”,但数据是“未定义”:

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

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

你能解释一下如何为下一个函数返回这些数据吗?

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

【问题讨论】:

    标签: angular ionic-framework return observable subscribe


    【解决方案1】:

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

    您可以做的最简单的事情是从订阅本身调用example()。像这样的东西应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2020-12-18
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多