简体   繁体   English

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

[英]Angular 6 change component if user is logged in

Using a JWT based implementation and Angular 6, what is the best way to hide/show components based on whether a user is logged in or not? 使用基于JWT的实现和Angular 6,根据用户是否登录隐藏/显示组件的最佳方法是什么? It would be nice to have an Observable user object that contains user related information. 拥有一个包含用户相关信息的Observable用户对象会很不错。 Does this require a Guard? 这需要看守吗?

The backend is using .NET Core 2.1, not sure if that makes a difference. 后端使用的是.NET Core 2.1,不确定这是否有所作为。 Most of this code is pulled from an old Angular Firebase project I was using to learn Angular, but I switched to .NET Core for several reasons. 大部分代码都是从我用来学习Angular的旧Angular Firebase项目中提取的,但我之所以切换到.NET Core有几个原因。 It was nice to have real time updates about the user which was using all sorts of Angular + Firebase magic. 很高兴有关于使用各种Angular + Firebase魔法的用户的实时更新。 Not sure how to repurpose this for .NET Core. 不知道如何为.NET Core重新利用它。

The login and logout functions do work, just not including the details of those components for brevity. 登录和注销功能确实有效,为简洁起见,不包括这些组件的详细信息。

Here is what I have so far: 这是我到目前为止:

auth.service.ts 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 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>

Add this code your AuthService: 添加此代码您的AuthService:

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

and login success response push data local storage and and authService 和登录成功响应推送数据本地存储和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'));
}

Contructor inside func listen to your user object and its change data set new value a your component variable. func中的contructor会监听你的用户对象,并将其更改数据设置为组件变量的新值。

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

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