繁体   English   中英

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

[英]Display components if there is an authenticated user

在angular 7应用程序中,我将在此处学习根据angularfire2文档实施身份验证。 我像这样设置了我的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

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。

我如何实现我的目标,我现在正在做某些事情吗?

我相信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>

订阅您的authState

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

您可以在那里设置用户。

你可以这样做 :-

在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'])]将其重定向到要重定向的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM