0
votes

I am trying to set up a basic auth within my Angular app, I have my firebase service which subscribes to the Auth change and has a function which is called within my login component when the form is submitted.

When using correct credentials the loggedIn always returns the following undefined value z {a: 0, i: undefined, c: z, b: null, f: null, …}, if you fill in the form with incorrect information the emailLogin function performs as expected and logs the error in the console. I'm not following why 'firebaseUser' is not returning anything for me to work with or at least see. I am new to Angular 2 and firebase so not 100% sure where the problems lies, whether it is with my component, service or firebase itself. Any help on the matter would be greatly appreciated. All of my code from the service and component can be seen below:

angularfire.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/observable';

import { UsersInterfaces } from '../users';

@Injectable()
export class AngularfireService {

    private users: Observable<UsersInterfaces.User>;

    public authState: any = null;

    public authError: any = null;

  constructor(private db: AngularFireDatabase, private fbAuth: AngularFireAuth) {
    // this.users = ;

    this.fbAuth.authState.subscribe((auth) => {
      this.authState = auth;
    })

  }

  public get allUsers() {
    return this.db.list('users').valueChanges();
  }

  public emailLogin(email: string, password: string){
    return this.fbAuth.auth.signInWithEmailAndPassword(email, password)
    .then((fireBaseUser) =>{
      this.authState = fireBaseUser;
    })
    .catch(error => {
        if (error.code === 'auth/invalid-email' || error.code === 'auth/wrong-password' || error.code === 'auth/user-not-found') {
            this.authError = 'The username and password you entered did not match our records. Please double-check and try again.';
        } else if (error.code === 'auth/user-disabled') {
            this.authError = 'Your account has been suspended. Please contact us directly to discuss this.';
      } else{
        this.authError = error.message;
      }
      console.log('Error: ',this.authError);
    })
  }

}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { AngularfireService } from '../core/angularfire/angularfire.service';

import { UsersInterfaces } from '../core/users';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})

export class LoginComponent {

  public form: FormGroup;

  private users: UsersInterfaces.User[];

    constructor(private fb: FormBuilder, private firebaseService: AngularfireService) {
        this.form = this.fb.group({
            email: '',
            password: ''
        })
    }

    public onSubmit(e) {

        const email = this.form.value.email;
        const password = this.form.value.password;

        const loggedIn = this.firebaseService.emailLogin(email,password);

        console.log(loggedIn)
    }

}
1
It is returning undefined because the signInWithEmailAndPassword is asynchronous. In fact, you should observe the change in the authState. - Cristiano Tenuta
@CristianoAndalóTenuta yeah, after taking some time away from the project and thinking about it some more I came to that realisation as well. Stupid on my part but solved it for the time being anyway! Thanks though! - LewisJWright

1 Answers

1
votes

Solved it! Changed authState and authError to be EventEmitters and just subscribe to those values in the login component. This will all eventually be moved to a different place and handled correctly anyway but for proof of concept this all works great!

angularfire.service.ts

@Output() public authState: EventEmitter<any> = new EventEmitter();

@Output() public authError: EventEmitter<any> = new EventEmitter();

public emailLogin(email: string, password: string) {
    this.fbAuth.auth.signInWithEmailAndPassword(email, password)
      .then((fireBaseUser) => {
        this.authState.emit(fireBaseUser);
      })
      .catch(error => {
          if (error.code === 'auth/invalid-email' || error.code === 'auth/wrong-password' || error.code === 'auth/user-not-found') {
              this.authError.emit('The username and password you entered did not match our records. Please double-check and try again.');
          } else if (error.code === 'auth/user-disabled') {
              this.authError.emit('Your account has been suspended. Please contact us directly to discuss this.');
          } else {
            this.authError.emit(error.message);
          }
      });
  }

login.component.ts

constructor(private fb: FormBuilder, private firebaseService: AngularfireService) {
        this.form = this.fb.group({
            email: '',
            password: ''
        });

        this.firebaseService.authState.subscribe(user => console.log(user));
        this.firebaseService.authError.subscribe(error => console.log(error));

    }