Error Alert on Login with firebase

Hi,

I want to get Alert on error on login with firebase … I have been trying few combinations but unable to understand why this code is not working:

Following is the TS for Login TS:

loginUser(): void {
    const loading = this.loadingCtrl.create();
    if (!this.loginForm.valid){
      console.log(this.loginForm.value);
    } else {
      this.authProvider.loginUser(this.loginForm.value.email, this.loginForm.value.password)
      .then( activeUser => {
        loading.dismiss().then( () => {
          if (activeUser === true){
            this.navCtrl.setRoot('TabsPage');
          } else {
            this.navCtrl.setRoot('WaitingPage');
          }
        })
      }, err => {
        let alert = this.alertCtrl.create({
          title: 'Error in Login',
          message: 'Please check your login credentials' + err + 'Pls try again',
          buttons: ['OK']
        });
        alert.present();
      });
    }
    loading.present();
  }

Following is the TS from the Auth Provider:

loginUser(email: string, password: string): Promise<any> {
    return new Promise( (resolve, reject) => {
      firebase.auth().signInWithEmailAndPassword(email, password).then( user => {
        firebase.database().ref(`/userProfile/${user.uid}`)
          .once('value', userProfile => {
            resolve(userProfile.val().active);
          }); 
      });
    });
  }

Any suggestions?

I would recommend https://javebratt.com/ it provides a free 71 page manual on using Firebase in Ionic and they will send you a link for the example code.

1 Like

Thanks. I have learnt a lot from Jorge. But the error seems coming due to some other non traceable reason… Pls suggest changes in codes if any

Can’t see all your code - this is what I do:

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, ToastController } from ‘ionic-angular’;
import { AngularFireAuth } from ‘angularfire2/auth’;

@IonicPage()
@Component({
selector: ‘page-login’,
templateUrl: ‘login.html’,
})
export class LoginPage {

 loginData = { email: '', password: ''}

 constructor(private navCtrl: NavController, private afAuth: AngularFireAuth, private toastCtrl: ToastController) { }

 login() {
      this.afAuth.auth.signInWithEmailAndPassword(this.loginData.email, this.loginData.password)
      .then(auth => {
           this.navCtrl.setRoot("HomePage");
      })
      .catch(err => { this.showToast(err); })
 }
1 Like

What error? Could you post it?

Any runtime error…

runtime

I want to capture auth errors:

"auth/wrong-password"
message
:
"The password is invalid or the user does not have a password."

These are basically errors which may arise on login due to wrong email/password entry

Pls suggest

I think your issue here is that you are not catching the error properly. You only have a resolve in your AuthProvider so you will never go in the error path in your login.ts. Try the code suggested by @JAR19 and put the alert code where he has this.showToast(err).

this.afAuth.auth.signInWithEmailAndPassword(this.loginData.email, this.loginData.password)
      .then(auth => {
           this.navCtrl.setRoot("TabsPage");
      })
      .catch(err => { 
          let alert = this.alertCtrl.create({
              title: 'Error in Login',
              message: 'Please check your login credentials' + err + 'Pls try again',
              buttons: ['OK']
          });
          alert.present(); 
      })
1 Like

This could be an issue… I want to check on the activeUser before directing to page. Also, there may be conflict since I am purely using firebase not AngularFire… I think, there should be a way in catching the errors even after validating active user…

I don’t get it - Why make it harder for yourself?

Not really… I am unable to get the activeUser through angfire… Active user based login is priority for me. The Promise method helps me sort out that…

this.afAuth.authState.subscribe(rawUser => { let user: firebase.User = rawUser as firebase.User)); console.log(user); });

I suggest you review the documentation - the login call returns
details about the user including the uuid key

Not really… I am unable to get the activeUser through angfire…
Active user based login is priority for me. The Promise method helps me
sort out that…

this.afAuth.auth.currentUser returns the user (if you want to avoid the subscription like @AaronSterling suggested)

Like @JAR19 said, it’s also returned by the signInWithEmailAndPassword function.

this.afAuth.auth.signInWithEmailAndPassword(this.loginData.email, this.loginData.password)
      .then(auth => { //auth is a firebase.User here
           this.navCtrl.setRoot("TabsPage");
      })

Made changes… But now not able to get the activeUser correctly…

loginUser(): void {    
    if (!this.loginForm.valid){
      console.log(`Form is not valid yet, value: ${this.loginForm.value}`);
    } else {
      const email = this.loginForm.value.email;
      const password = this.loginForm.value.password;
      this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then(userProfile => {
        if (userProfile.active === true){
          this.navCtrl.push('TabsPage');
        } else {
          this.navCtrl.push('WaitingPage')
        }
      }, error => {
        let alert = this.alertCtrl.create({
          title: 'Login Error',
          message: error + 'Pls try again',
          buttons: ['OK']
        });
        alert.present();
      })
    }
  }

active is not a property of firebase.User and it seem like this property is in your userProfile table

You could do

this.afAuth.auth.signInWithEmailAndPassword(email, password)
     .then(user => {
       this.afDatabase.object("/userProfile/" + user.uid).subscribe(userProfile => {
         if (userProfile.active === true){
           this.navCtrl.push('TabsPage');
         } else {
           this.navCtrl.push('WaitingPage')
         }
       })
     }, error => {
       let alert = this.alertCtrl.create({
         title: 'Login Error',
         message: error + 'Pls try again',
         buttons: ['OK']
       });
       alert.present();
     })

Fantastico!!! Finally… Small change… instead of once used subscribe… Thank you so much @QGangler and @JAR19 … Although it did solve the issue… I am still not clear how to use Promise to get the error … Loads to learn. Thanks again!

Yeah, I’m still learning on Observables (the whole deal with once and subscribe) so my answer might not be perfect (feel free to correct me).

What’s not working there? The error should be present in your alert

Thanks. You are still way better. I think the problem is not with error in alert(it was there earlier too) but the problem is with resolve not letting error show… or may be reject needs to be handled appropriately. Shall go through the docs again. All the best!