使用基于 JWT 的实现和 Angular 6,根据用户是否登录隐藏/显示组件的最佳方式是什么?如果有一个包含用户相关信息的 Observable 用户对象就好了。这需要 guard 吗?
后端使用的是 .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>
最佳答案
将此代码添加到您的 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 中的构造函数监听您的用户对象及其更改数据,将新值设置为您的组件变量。
关于如果用户已登录,则 Angular 6 更改组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352673/