0

I have an Angular pipe which checks if a user is a premium member before navigate to specific routes.

Premium Guard:

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;
    }
  })
)

But as not logged in user I get always many errors in console user is null. How could I check is an user is logged in before?

The following is not working:

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;
    }
  })
)

Do you have another idea? Thanks in advance!

Vueer
  • 1,432
  • 3
  • 21
  • 57

1 Answers1

0

Your last approach is not working because your switchMap will return false if the user is null, and you would like to work with it like a profile variable later.

The easiest and fastet but not elegant solution is to return an empty array or [{premium: false}] array instead of false in the switchMap.