如果用户已登录,则Angular 6更改组件

时间:2018-07-15 22:28:22

标签: angular authentication asp.net-core jwt

使用基于JWT的实现和Angular 6,根据用户是否登录来隐藏/显示组件的最佳方法是什么?拥有一个包含与用户相关的信息的Observable用户对象会很好。这需要警卫吗?

后端使用的是.NET Core 2.1,不确定是否有所不同。大部分代码是从我用来学习Angular的旧Angular Firebase项目中提取的,但是出于多种原因,我切换到.NET Core。拥有使用各种Angular + Firebase魔术的用户的实时更新真是太好了。不确定如何将其重新用于.NET Core。

登录和注销功能确实起作用,只是为了简洁起见,不包括这些组件的详细信息。

这是我到目前为止所拥有的:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from "@angular/router";
import { Observable } from 'rxjs';

interface User {
  email: string;
  password: string;
}

@Injectable()
export class AuthService {

  user: Observable<User>;
  invalidLogin: boolean;

  constructor(
    private http: HttpClient,
    private router: Router
  ) { }

  login(e: string, p: string) {
    let credentials = { email: e, password: p}
    this.http.post("https://localhost:44368/api/auth/login", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    }).subscribe(response => {
      let token = (<any>response).token;
      localStorage.setItem("jwt", token);
      this.invalidLogin = false;
      this.router.navigate(["/dashboard"]);
      console.log('Access granted.');
    }, err => {
      this.invalidLogin = true;
      console.log('Access denied.');
    });
  }

  logout() {
    localStorage.removeItem("jwt");
    this.router.navigate(["/"]);
  }
}

my.component.html

<div *ngIf="auth.user | async; then authenticated else guest">
  <!-- Template will replace this div -->
</div>

<ng-template #guest>
  <p>Guest</p>
</ng-template>

<ng-template #authenticated>
  <p>Authenticated</p>
</ng-template>

1 个答案:

答案 0 :(得分:3)

将此代码添加到您的AuthService:

private user = new Subject<User>();
public userEmitter = this.user.asObservable();
userEmitChange(usr: User) {
    this.user.next(usr);
}

和登录成功响应将数据推送到本地存储和authService

  localStorage.setItem('currentUser', JSON.stringify(res));
  this.authService.userEmitChange(res);

现在像下面这样使用此变量的所有组件:

constructor(private authService: AuthService) {
  this.authService.userEmitter.subscribe(user => {
    this.user = user;
  });

  this.user = JSON.parse(localStorage.getItem('currentUser'));
}

func内部的构造函数侦听您的用户对象,其更改数据将新值设置为组件变量。