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