0

我在 angularfire2 中执行操作,我订阅了 angularfire.auth,以便使用以下代码检索当前登录用户的用户 ID:

angularfire.auth.subscribe(auth => {
      this.userId = auth.uid;
      console.log(this.userId);
  }

这成功地工作并将 uid 分配给局部变量 userId。

我遇到的问题是当我希望执行以下代码时:

let shipObservable = angularfire.database.list('/ships/' + this.userId);

    shipObservable.subscribe(
        value => {
            this.otherObservable = angularfire.database.list('/other/' + value[0].otherId);
            this.otherObservable.subscribe(value => {
                this.address = value[0].$value;
                this.number = value[1].$value;
                this.email = value[2].$value;
                this.name = value[3].$value;
                });
    }).catch((err) => console.log(err));

问题是第二段代码在我从第一个 observable 取回 uid 之前运行。我知道这些是异步操作,可能随时回来。但我想知道是否有办法确保在将用户 id 分配给 auth 返回的 uid之后执行第二个 observable。

4

1 回答 1

0

我已经使用作为RXJS一部分的switchMap 运算符解决了这个问题。在下面的片段中,我假设“afAuth”是对 firebase auth 对象的引用,而“af”是对 firebase 数据库对象的引用。

authState$ = afAuth.authState;
shipObservable$ = authState$.switchMap((auth) => {
    return af.list('ships/' + auth.uid);
});

要使用 switchMap 你需要导入操作符:

import 'rxjs/add/operator/switchMap';
于 2017-08-03T08:00:37.590 回答