【问题标题】:Why is angularfire (afAuth.user | async) as user different than afAuth.user.subscribe为什么 angularfire (afAuth.user | async) 作为用户不同于 afAuth.user.subscribe
【发布时间】:2020-04-23 14:33:32
【问题描述】:

我很好奇为什么这些对象是不同的。我有一个简单的 Angular 组件如下:

user.component.html

  <pre *ngIf="(afAuth.user | async) as user"> {{ user | json }}</pre>

我使用它是为了查看用户的属性。

user.component.ts

constructor(private afAuth: AngularFireAuth) {

  this.afAuth.user.subscribe(val => {
  console.log('user change', val);
  this.updateUserData(val);
});

}

但是,订阅中返回的“val”对象与视图中显示的不同。 为什么视图中显示的对象与我手动订阅时返回的对象不同?

我的理解是异步管道只是为您订阅。我错过了什么?

我问是因为我想访问 user.lastLoginAt 和 user.createdAt 属性并将它们存储在 firestore 中。

在视图截图中:

console.log(val) 控制台截图:

【问题讨论】:

  • 您能否在问题中添加两个回答,val 对象是什么
  • 好的,添加截图。
  • 请您提供打印 val 的代码吗?
  • 已更新,在订阅中。
  • 你试过console.log(JSON.stringify(val))吗?

标签: angular typescript firebase firebase-authentication angularfire2


【解决方案1】:

如果您在模板中使用async,则模板中不应有.subscribe。我怀疑是模板变量是这个方法的返回this.updateUserData(val);

您需要使用RxJS 中的tap 运算符来执行任何可能有副作用的操作。

this.afAuth.user
  .pipe(
    tap((val) => {
      // any code in here will not change the `val`
      this.updateUserData(val);
    })
  )
  .subscribe(val => {
    console.log('user change', val);
  });

我还建议在您的类中创建服务方法的引用并在您的模板中使用它。

@Component()
class UserComponent {
  authUser = this.afAuth.user;
}

另外需要注意的是| json 管道调用了对象上的toJSON 方法。所以...

如果被字符串化的对象有一个名为 toJSON 的属性,其值为一个函数,则 toJSON() 方法自定义 JSON 字符串化行为:而不是被序列化的对象,调用时 toJSON() 方法返回的值将是序列化。 JSON.stringify() 使用一个参数调用 toJSON:

firebase.auth 对象可能有自定义返回。

在您的代码中; user.lastLoginAtuser.createdAt 实际上可以在模板中访问,但在 {{user | json}} 输出中不可见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2018-07-15
    相关资源
    最近更新 更多