刷新页面时Angular和JWT角色消失

时间:2018-10-12 21:43:13

标签: angular typescript jwt

我正在使用身份验证部分对CRUD应用程序进行编码,因此我使用JWT的角色来管理页面之间的方向,因此当用户登录到应用程序时,他将仅在菜单中看到与其角色相关的链接。

AuthenticationService.ts

var el=document.getElementById('mySelect');
el.selectedIndex = el.options.findIndex(x => x.value === 'Apple')

app.component.html

import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {JwtHelper} from 'angular2-jwt';

@Injectable()
export class AuthenticationService {

  private host:string="http://localhost:8080";
  private jwtToken:string=null;
  private roles:Array<any>=[];
  private tk:any;

  constructor(private http:HttpClient){

  }
  login(user){
    return this.http.post(this.host+"/login",user, {observe:'response'});
  }

  logout(){
    this.jwtToken=null;
    localStorage.removeItem('token');
  }

  saveToken(jwt:string){
    this.jwtToken=jwt;
    localStorage.setItem('token',jwt);
    let jwtHelper=new JwtHelper();
    this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
  }

  loadToken(){
    return this.jwtToken=localStorage.getItem('token');
  }

  isAdmin(){
    for(let r of this.roles) {
      console.log("********************************"+r);
      if(r.authority=='ADMIN') return true;
    }
    return false;
  }
  isDeveloper(){
    for(let r of this.roles) {
      console.log("********************************"+r);
      if(r.authority=='DEVELOPER') return true;
    }
    return false;
  }
  isCommercial(){
    for(let r of this.roles) {
      console.log("********************************"+r);
      if(r.authority=='COMMERCIAL') return true;
    }
    return false;
  }

  isOnline(){
    this.jwtToken=localStorage.getItem('token');
    if (this.jwtToken != null) return true;
    return false;
  }
  isOffline(){
    this.jwtToken=localStorage.getItem('token');
    if (this.jwtToken == null) return true;
    return false;
  }

}

问题是,当用户登录后,菜单很好,但是当他刷新页面或单击上一页或下一页时,菜单中具有上述条件的链接消失了,但用户仍在登录。 我怎么解决这个问题?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

like @ user184994说我需要加载这样的角色:

isAdmin(){
    let jwtHelper=new JwtHelper();
    this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
    for(let r of this.roles) {
      console.log("********************************"+r);
      if(r.authority=='ADMIN') return true;
    }
    return false;
  }