无法将Firebase Auth连接到Angular Web App,页面仅重新加载

时间:2019-06-22 16:06:47

标签: angular typescript firebase firebase-authentication

一段时间以来,我一直在尝试实施Firebase Auth。我遵循了很多教程,但是this one代表了我当前的代码版本。

我将AngularFireModuleAngularFireAuthModule导入了app.module.ts。另外,我创建了以下服务,并创建了一个从服务中调用方法的登录名。

我知道该服务已成功调用,因为console.log返回正确的输入。此外,页面会重新加载,但没有任何反应(重新加载时会在链接中添加“?”)。

有人知道这个问题吗?我已经在使用Firebase托管,因此我假设我已经正确实现了Firebase。

export class AuthService {
  user: User;


  constructor(public afAuth: AngularFireAuth, public router: Router) {
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.user = user;
        localStorage.setItem('user', JSON.stringify(this.user));
      } else {
        localStorage.setItem('user', null);
      }
    });
  }

  async login(email: string, password: string) {
    try {
      console.log('uff');
      await  this.afAuth.auth.signInWithEmailAndPassword(email, password);
      this.router.navigate(['admin']);
    } catch (e) {
      alert('Error!'  +  e.message);
    }
  }

  get isLoggedIn(): boolean {
    const  user  =  JSON.parse(localStorage.getItem('user'));
    return  user  !==  null;
  }

  async logout() {
    await this.afAuth.auth.signOut();
    localStorage.removeItem('user');
    this.router.navigate(['']);
  }

}

路由:

const routes: Routes = [
  { path: '', component: FrontComponent },
  { path: 'cases', component: CaseListComponent },
  { path: 'cases/:id', component: TemplateComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'admin', component: AdminComponent, children: [
      { path: '', redirectTo: 'front', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      { path: 'front', component: FrontComponent },
    ]},
];

登录:

<div class="container-fluid min-vh-100 d-flex justify-content-center">

  <form class="align-self-center">
    <div class="form-group">
      <label for="email">Email address</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" #email required>
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control" id="password" placeholder="Password" #password required>
    </div>
    <button class="btn btn-primary" (click)="authService.login(email.value, password.value)">Submit</button>
  </form>

</div>

<li *ngIf="authService.isLoggedIn" class="nav-item">
  <a class="nav-link"  (click)="authService.logout()">Logout</a>
</li>



Typescript:
constructor(public authService: AuthService) { }

0 个答案:

没有答案