Angular Firebase: Accessing field maps for authentication

Refresh

6 days ago

Views

25 time

2

I have a firebase collections of users > document id > uid, ..., and roles { admin: boolean, moderator: boolean, client: boolean }. My authentication process works correctly with the guards redirecting as needed. More importantly I am display 90% of the data in applicable components within my users dashboard.

Problem is that when I reference {{ user.roles.admin }} using ngIf in a component, I get the error:

ERROR TypeError: Cannot read property 'admin' of undefined at Object.eval [as updateRenderer]  

Funny thing is that I can't fix either issue with playing around with the code to try and grab the information, but I can adjust and send what ever I want back to Firebase. I need someone to point me in the right direction.

Model:

export interface User {
  uid: string;
  email: string;
  photoURL?: string;
  displayName?: string;
  roles: Roles;
}

export interface Roles {
  admin?: boolean;
  moderator?: boolean;
  client?: boolean; 
}  

Auth Service:

import { Injectable, NgZone } from '@angular/core';
import { User } from "../../models/user/user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  userData: any; 
  constructor(
    public afs: AngularFirestore,   
    public afAuth: AngularFireAuth, 
    public router: Router,  
    public ngZone: NgZone 
  ) {    
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }
  SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['account']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }
  ...
  ...
  ...
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }
  ...
  AuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
    .then((result) => {
       this.ngZone.run(() => {
          this.router.navigate(['account']);
        })
      console.log('User', result.user);
      this.SetUserData(result.user);
    }).catch((error) => {
      window.alert(error)
    })
  }
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
    const userData: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      roles: {
        client: true
      }
    }
    return userRef.set(userData, {
      merge: true
    })
  }
  ...
}

1 answers

0

Это, как я проверить пользователя в компоненте HTML:

*ngIf="user && user.role?.admin"

машинопись:

getUser() {
 this.authService.user$.subscribe(user => {this.user = user});
}

и это от Идентой службы:

  user$: Observable<User>;
  authState: any = null;

  constructor (
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }