如果有经过身份验证的用户,则显示组件

Display components if there is an authenticated user

在 angular 7 应用程序中,我正在学习根据 angularfire2 文档 here 实施身份验证。我这样设置 app.component.html 文件

<app-login *ngIf="!authService.user"></app-login>

<div class="container-fluid" *ngIf="(authService.user | async) as user">
  <div class="row">
    <!-- navigation sidebar -->
    <div class="col-2 pt-5" id="sideNav">
      <app-navbar></app-navbar>
    </div>

    <!-- main content area -->
    <main class="col-10 offset-2">
      <router-outlet></router-outlet>
    </main>
  </div>
</div>

所以如果有认证用户,则不会渲染登录组件。我有一个使用 AngularFireAuth

的 authenticate.service.ts
import { Injectable } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
import { auth } from "firebase/app";

@Injectable({
  providedIn: "root"
})
export class AuthenticateService {
  constructor(private afAuth: AngularFireAuth) {}

  signinUser(email: string, password: string) {
    this.afAuth.auth.signInWithEmailAndPassword(email, password);
    console.log("logged in");
  }
}

我的 login.component.ts 导入身份验证服务并在用户提供电子邮件和密码时尝试登录用户

import { NgForm } from "@angular/forms";
import { Component, OnInit } from "@angular/core";
import { AuthenticateService } from "../services/authenticate.service";
import { Router } from "@angular/router";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
  user = null;

  constructor(private authService: AuthenticateService) {}

  ngOnInit() {}

  tryLogin(loginForm: NgForm) {
    const email = loginForm.value.email;
    const password = loginForm.value.password;

    console.log(email, password);

    this.authService.signinUser(email, password);
  }
}

我的登录组件按预期呈现,我在尝试登录时看到预期的 console.log 消息,但我的视图没有按预期更改 - 即呈现 div 包含导航和主要内容区。

我如何实现我的目标,我是否遗漏了我现在正在做的事情?

订阅您的 authState

this.afAuth.authState.subscribe(user => {
   // your code
});

在那里你可以设置你的用户。

我相信signInWithEmailAndPassword应该是异步的,所以你需要等待它解决:

this.afAuth.auth.signInWithEmailAndPassword(email, password)
  .then(response => console.log(response));

我不确定响应的确切类型是什么,但您应该将其保存在您的身份验证服务中:

export class AuthenticateService {
  public user: BehaviorSubject<any> = new BehaviorSubject(null); // Add type accordingly

  constructor(private afAuth: AngularFireAuth) {}

  signinUser(email: string, password: string) {
    this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then(response => { console.log('Logged in!'; this.user.next(response); });
  }
}

将您的 authService 添加到 AppComponent:

constructor(private myAuthService: AuthenticateService ) {}

然后在 app.component.html 中查找登录用户,如下所示:

<app-login *ngIf="!(myAuthService.user | async)"></app-login>

<div class="container-fluid" *ngIf="(myAuthService.user | async) as user">
  <div class="row">
    <!-- navigation sidebar -->
    <div class="col-2 pt-5" id="sideNav">
      <app-navbar></app-navbar>
    </div>

    <!-- main content area -->
    <main class="col-10 offset-2">
      <router-outlet></router-outlet>
    </main>
  </div>
</div>

你可以这样做:-

在signin.component.ts

 onSignIn(form: NgForm){
            const email = form.value.email;
            const password = form.value.password;
            this.authService.signInUser(email, password);
        }

在AuthService.ts

signInUser(email: string, password: string) {
        firebase.auth().signInWithEmailAndPassword(email, password)
            .then(
                response => {
                   //check if response is correct here
                    this.router.navigate(['your_component_route']);
                    firebase.auth().currentUser.getIdToken()
                        .then(
                            (token: string) => this.token = token
                        )
                }
            ).catch(
                error => console.log(error)
            )
    }

所以基本上你必须使用 router.navigate[(['Your_Route'])]

将它重定向到你想重定向的地方