【问题标题】:How to wait for a subscription to complete angular如何等待订阅完成角
【发布时间】:2017-09-01 12:27:00
【问题描述】:

我有一个身份验证服务,我想在它返回之前使用 angularfire 从 firebase 检索用户记录,但数据返回得太晚了。我添加了“.filter(data => data !== undefined)”,但它并没有导致它等待。

this.authState = this.afAuth.authState;
this.authState.subscribe(user => {
  if (user) {
    this.currentUser = user;
    this.userid = this.currentUser.uid;
    this.displayname = this.currentUser.displayName;
    this.path = '/AU/user/' + this.currentUser.uid + '/';
    this.exists = this.af.object(this.path);
      // this line of code returns data after the navbar 
      // and user components have started which is too late.
      // The filter was added to try to get it wait for the data.
    this.exists.filter(data => data !== undefined).subscribe(x => {

      if (x && (x.$value !== null)) {
        this.mobile = x.mobile;
        this.userid = x.userid;
        this.name = x.name;
        this.email = x.email;
        this.confirm = x.confirm;
          // the fields below are undefined in the console log
        console.log( 'email', this.email, 'name', this.name)
      } else {
        this.currentUser = null;
      }
  });

在谷歌上搜索这个问题时,我发现也许我需要映射响应,但这没有任何区别。下面是我使用的代码

 this.exists.map(response => this.response$)
            .filter(data => data !== undefined)
            .subscribe(x => {

我尝试比较“未定义”和“空”。我的想法已经用完了,请帮忙。

【问题讨论】:

    标签: angular asynchronous angular2-services angular2-observables


    【解决方案1】:

    像这样使用flatMap()怎么样?

    import 'rxjs/add/operator/mergeMap`;
    
    this.exists.flatMap(response => {
      this.response$
      .catch(error => {
        console.error(error);
        return Rx.Observable.empty();
      });
    });
    

    我导入了mergeMap 运算符,尽管我们将使用flatMap,因为flatMap missing after upgrading to RC 6 and RxJS Beta 11rxjs flatmap missing

    如果您愿意,请阅读map vs flatMap

    【讨论】:

    • 这样更好:)
    • 这太荒谬了,你为什么要复制我的答案?你本可以添加评论)这样的支持需要:
    • @Milad 如果您有这样的印象,我很抱歉。事实是我没有看到你的答案,因为我们是同时发的。
    【解决方案2】:
     this.exists.flatMap(response => this.response$)
    

    【讨论】:

    • 谢谢。我收到一个错误“TypeError: _this.exists.flatMap is not a function”我添加了“import 'rxjs/add/operator/flatMap'但无法解析'rxjs/add/operator/flatMap'
    • 我做了更改错误消失了谢谢你不幸的是“.filter(data => data!== undefined)”没有达到我的预期。我确实保留了数据流,但订阅似乎继续它的快乐方式并崩溃“util.js:233 FIREBASE WARNING:用户回调引发异常。TypeError:您在预期流的位置提供了“未定义”。你可以提供 Observable、Promise、Array 或 Iterable。”回到绘图板。感谢您的帮助。
    • 你确定 this. existsthis.response$ 是 Observables 吗?向我们展示代码
    • 它太长了 1500 个字符。除了上面的代码还有:
    • 还是太长了。我不知道 this.response$ 需要设置为 observable。我该怎么做? this.exists 就像我之前在这个项目中使用过的一样,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2019-03-24
    • 1970-01-01
    • 2019-09-23
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多