如果用户已登录,Angular 6更改组件 [英] Angular 6 change component if user is logged in
问题描述
使用基于JWT的实现和Angular 6,根据用户是否登录来隐藏/显示组件的最佳方法是什么?拥有一个包含用户相关信息的Observable用户对象将是一个很好的选择.这需要警卫吗?
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?
后端使用的是.NET Core 2.1,不确定是否有所不同.大部分代码是从我用来学习Angular的旧Angular Firebase项目中提取的,但出于以下几个原因,我切换到了.NET Core.拥有使用各种Angular + Firebase魔术的用户的实时更新真是太好了.不确定如何将其重新用于.NET Core.
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>
推荐答案
将此代码添加到您的AuthService:
private user = new Subject<User>();
public userEmitter = this.user.asObservable();
userEmitChange(usr: User) {
this.user.next(usr);
}
和登录成功响应将数据推送到本地存储和authService
and login success response push data local storage and and 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内部的构造函数侦听您的用户对象,其更改数据将新值设置为您的组件变量.
Contructor inside func listen to your user object and its change data set new value a your component variable.
这篇关于如果用户已登录,Angular 6更改组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!