Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreionic4

IONIC 4 - Angular / Firestore


I'm facing to a problem concerning authentication and user profile. I'm using ionic v4 / angular and firestore. Currently I can login by email and password but when I would like to go in profile to get this user data, I'm facing to a blank page.

Here my user.service.ts

import { Injectable } from '@angular/core'
import { AngularFireAuth } from '@angular/fire/auth'
import { first } from 'rxjs/operators'
import { auth } from 'firebase/app'

interface user {
    username: string,
    uid: string
}

@Injectable()
export class UserService {
    private user: user

    constructor(private afAuth: AngularFireAuth) {

    }

    setUser(user: user) {
        this.user = user
    }

    getUsername(): string {
        return this.user.username
    }

    reAuth(username: string, password: string) {
        return this.afAuth.auth.currentUser.reauthenticateWithCredential(auth.EmailAuthProvider.credential(username, password))
    }

    updatePassword(newpassword: string) {
        return this.afAuth.auth.currentUser.updatePassword(newpassword)
    }

    updateEmail(newemail: string) {
        return this.afAuth.auth.currentUser.updateEmail(newemail)
    }

    async isAuthenticated() {
        if(this.user) return true

        const user = await this.afAuth.authState.pipe(first()).toPromise()

        if(user) {
            this.setUser({
                username: user.email.split('@')[0],
                uid: user.uid
            })

            return true
        }
        return false
    }

    getUID(): string {
        return this.user.uid
    }
}

Here my login.page.ts

export class LoginPage implements OnInit {

    username: string = ""
    password: string = ""

    constructor(public afAuth: AngularFireAuth, public user: UserService, public router: Router) { }

    ngOnInit() {
    }

    async login() {
        const { username, password } = this
        try {
            // kind of a hack. 
            const res = await this.afAuth.auth.signInWithEmailAndPassword(username, password)

            if(res.user) {
                this.user.setUser({
                    username,
                    uid: res.user.uid,
                })
                console.log(res.user.uid)
                this.router.navigate(['/home-results'])
            }

        } catch(err) {
      alert("Bad Credentials")
            console.dir(err)
            if(err.code === "auth/user-not-found") {
                console.log("User not found")
            }
        }
    }
}

profil.page.ts

@Component({
  selector: 'app-profil',
  template: `
  <!-- User logged in -->
  <ng-template #authenticated>
  <div *ngIf="auth.user | async as user">
    <h3>Howdy, {{ user.username }}</h3>
    <p>UID: {{ user.uid }}</p>
    <!-- <p>Favorite Color: {{ user.countryBirth }} </p> -->
    <button (click)="auth.signOut()">Logout</button>
  </div>
  </ng-template>`,


  styleUrls: ['./profil.page.scss'],
})
export class ProfilPage {

  constructor(public auth: AuthService ,public user:UserService){}

}

Solution

  • Finally, I found and resolved my issu.

      constructor(
        private afAuth: AngularFireAuth,
        private afs: AngularFirestore,
        private router: Router,
        public auth: AuthService
      ) {
        this.user$ = this.afAuth.authState.pipe(
          switchMap(user => {
            if (user) {
              console.log(user.email)
              console.log(user.uid)
              return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
            } else {
              return of(null);
            }
          })
        );
      }