Angular 6 change component if user is logged in

删除回忆录丶 提交于 2021-01-27 13:22:52

问题


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? It would be nice to have an Observable user object that contains user related information. Does this require a Guard?

The backend is using .NET Core 2.1, not sure if that makes a difference. 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. It was nice to have real time updates about the user which was using all sorts of Angular + Firebase magic. Not sure how to repurpose this for .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

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:


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

  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.



来源:https://stackoverflow.com/questions/51352673/angular-6-change-component-if-user-is-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!