【问题标题】:Check if user is null in Angular Guard检查用户在 Angular Guard 中是否为空
【发布时间】:2020-10-14 21:43:50
【问题描述】:

我有一个 Angular 管道,可以在导航到特定路线之前检查用户是否是高级会员。

高级保护:

return this.afAuth.authState.pipe(
  take(1),
  switchMap(user => {
    return this.db.getUserWithKey(user.uid)
  }),
  map((profile) => {
    if (profile.length && profile[0].premium) {
      return true
    } else {
      location.href = "https://url.com";
      return false;
    }
  })
)

但是由于没有登录用户,我总是在控制台user is null 中遇到很多错误。如何检查用户之前是否登录过?

以下内容不起作用:

return this.afAuth.authState.pipe(
  take(1),
  switchMap(user => {
    if (!user || user == null) {
      return false;
    }
    return this.db.getUserWithKey(user.uid)
  }),
  map((profile) => {
    if (profile.length && profile[0].premium) {
      return true
    } else {
      location.href = "https://url.com";
      return false;
    }
  })
)

你还有别的想法吗?提前致谢!

【问题讨论】:

    标签: angular typescript firebase angular-guards


    【解决方案1】:

    您的最后一种方法不起作用,因为如果用户为 null,您的 switchMap 将返回 false,并且您希望稍后像 profile 变量一样使用它。

    最简单快捷但不优雅的解决方案是在 switchMap 中返回一个空数组或[{premium: false}] 数组而不是 false。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2018-11-03
      • 2018-08-23
      相关资源
      最近更新 更多