简体   繁体   English

如果已登录用户,则隐藏 Angular 中的 div

[英]hide div in Angular if is logged in user

I try to hide a div when the user is logged in, using auth service in Angular and token from Django我尝试在用户登录时隐藏 div,使用 Angular 中的身份验证服务和 Django 中的令牌

Component.html组件.html

<a *ngIf="authService.isLogedin()" style="color:white"   href="/#/login" class="nav-link" (click)="logOut()">Cerrar sesión</a>

auth service.ts身份验证服务.ts

islogedin: boolean = false;

private setSession(authResult) {
  const token = authResult.token;
  const payload = <JWTPayload> jwtDecode(token);
  const expiresAt = moment.unix(payload.exp);

  localStorage.setItem('token', authResult.token);
  localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf()));
}

isLogedin() {

    if (JSON.parse(localStorage.getItem('token')).auth_token == null) {
      this.islogedin = false;
      return this.islogedin;
    }
    else {
      return true;
    }
  }

You can't call the service directly into the html component不能将服务直接调用到 html 组件中

You have to make the service injection in the constructor and use that it in您必须在构造函数中进行服务注入并在其中使用它

In component.ts在组件.ts

islogedin: boolean;

constructor (private authService:AuthService)
{islogedin= authService.isLogedin();

}

Then in html component use like this然后在 html 组件中像这样使用

component.html组件.html

         <a *ngIf="islogedin" style="color:white"   href="/#/login" class="nav-link" (click)="logOut()">Cerrar sesión</a>

Try next, to prevent errors in JSON.parse.接下来尝试,以防止 JSON.parse 中的错误。

isLogedin() {
   const token = localStorage.getItem('token');
   this.islogedin = token && JSON.parse(token) != null;
   return this.islogedin;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM