Angular JWT令牌刷新

时间:2020-05-09 22:33:04

标签: angular .net-core jwt

我使用JWT身份验证令牌将这个有角度的应用程序与.Net Core后端一起使用。一切都运行良好,除了这一件事:发生登录时,应该立即显示一个按钮(仅在本地存储中存在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;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

登录成功后,您可以使用对象通知组件更新模板

auth.service.ts

loginSubject = new BehaviorSubject<boolean>(false);

setLogin(status) {
  this.loginSubject.next(status);
}

然后在设置this.toastr.success / this.toastr.error后使用setLogin(true)

top-bar.component.ts

ngOnInit(): void {
  this.authService.loginSubject.subscribe(
    status => this.isLoggedIn = status
  )
}