首页 文章

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

提问于
浏览
2

使用基于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 回答

  • 2

    Add this code your 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);
    

    Now use this variable all component like this:

    constructor(private authService: AuthService) {
      this.authService.userEmitter.subscribe(user => {
        this.user = user;
      });
    
      this.user = JSON.parse(localStorage.getItem('currentUser'));
    }
    

    func中的contructor会监听您的用户对象,并将其更改数据设置为组件变量的新值 .

相关问题