【发布时间】:2020-08-25 12:23:24
【问题描述】:
我有这个带有 .Net Core 后端的 Angular 应用程序,使用 JWT 身份验证令牌。一切都运行良好,除了这一点:登录发生时,应该立即出现一个按钮(仅当本地存储中存在 JWT 时)......但它没有!只有当我刷新页面时,按钮才会出现在导航栏中!无论如何我可以解决这个问题吗?提前致谢!
这是我使用变量“isLoggedIn”的组件,因此按钮是否显示: top-bar.component.html
<mat-toolbar class="mat-elevation-z10 toolbar-style">
<a [routerLink]="['/']">
<img class="top-bar-logo" src="assets/Images/DocShareAppLogo.png" alt="DocShareApp-Automobile">
</a>
<span class="spacer"></span>
<div class="spaceInButtons" *ngIf="isLoggedIn">
<mat-menu #appAccountMenu="matMenu">
<button routerLink="personalInfo" mat-menu-item>Personal Info</button>
</mat-menu>
<a mat-raised-button class="account-button-color" [matMenuTriggerFor]="appAccountMenu">
My Account
</a>
</div>
<mat-menu #appFabAccount="matMenu">
<button routerLink="registerLogin" mat-menu-item>Register/Login</button>
</mat-menu>
<a mat-fab class="account-button-color" [matMenuTriggerFor]="appFabAccount">
<mat-icon>account_circle</mat-icon>
</a>
</mat-toolbar>
top-bar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../shared/auth.service';
@Component({
selector: 'app-top-bar',
templateUrl: './top-bar.component.html',
styleUrls: ['./top-bar.component.css']
})
export class TopBarComponent implements OnInit {
isLoggedIn = false;
constructor(private authService: AuthService) { }
ngOnInit(): void {
this.isLoggedIn = this.authService.isAuthenticated();
}
}
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormGroupDirective } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class AuthService {
readonly rootURL = 'https://localhost:5001/';
constructor(private httpClient: HttpClient, private toastr: ToastrService, private router: Router) { }
postLogin(formModel: FormGroup, formDirective: FormGroupDirective){
return this.httpClient.post(this.rootURL + 'Users/login', formModel).subscribe(
(response: any) => {
if (response.succeeded)
formModel.reset();
formDirective.resetForm();
localStorage.setItem('token', response.token);
//localStorage.removeItem('token');
this.router.navigateByUrl('/');
this.toastr.success('You have been logged in', response.message, { positionClass: 'toast-top-right' } )
},
errorResponse => {
this.toastr.error(errorResponse.error.message, 'Login unsuccessful', { positionClass: 'toast-top-right' });
}
);
}
isAuthenticated(): boolean{
if (localStorage.getItem('token')){
return true;
}
else{
return false;
}
}
}
【问题讨论】:
-
请贴出容易出错的代码。
-
我发布了服务类,如果您需要html或其他内容,请告诉我
-
将代码发布为图像使其难以复制。一个更好的版本将是一个最小的工作示例(例如使用 Stackblitz)。是的,没有模板就不清楚了。
-
您的
isAuthenticated()检查发生在postLogin()检查之前吗?发布您的模板代码! -
isAuthenticated() 被调用,因此检查令牌是否在本地存储(浏览器)中,如果是,则证明用户的 postLogin() 成功(因为服务器返回了一个jwt),所以会出现navbar上的按钮!