Angular firebase auth服务 - 用户始终未定义

时间:2018-02-17 11:52:05

标签: angular firebase firebase-authentication angularfire2

我正在尝试在我的Angular应用程序中设置一个基本身份验证,我有我的firebase服务,它订阅了Auth更改,并且在提交表单时有一个在我的登录组件中调用的函数。

使用正确的凭据时,loggedIn始终返回以下未定义的值z {a: 0, i: undefined, c: z, b: null, f: null, …},如果您使用不正确的信息填写表单,则emailLogin函数将按预期执行,并在控制台中记录错误。我不遵循为什么&firesenUser'我没有为我工作或至少看到任何东西。我是Angular 2和firebase的新手,因此不能100%确定问题所在,无论是我的组件,服务还是firebase本身。任何有关此事的帮助将不胜感激。我在服务和组件中的所有代码都可以在下面看到:

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 个答案:

答案 0 :(得分:1)

解决了!已将authStateauthError更改为EventEmitters,只需在登录组件中订阅这些值即可。这最终都会被移到另一个地方并且无论如何都要正确处理,但为了概念验证,这一切都很有效!

<强> 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));

    }