Angular(5) - 登录成功登录后,登录按钮不会更改为退出

时间:2017-12-05 19:13:35

标签: angular rxjs auth0

我使用Auth0的API来处理用户管理。一切都按预期工作 - 在Login()正确存储本地。在Logout()上,它会正确删除它们。

但是,实际Login按钮在成功时不会自动成为Logout - 这是我硬翻页面时,而不是直接刷新页面。我相信这是我绑定的问题吗?

标题组件

  authenticated: boolean; // Wasn't sure how else to filter in front-end

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authenticated = this.authService.isAuthenticated()
  }



  login() {
    this.authService.login();
  }

  logout() {
    this.authService.logout();
  }

}

HTML代表标题

  <li class="nav-item">
    <a class="nav-link waves-light" *ngIf="!authenticated" mdbRippleRadius (click)="login()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log In</span></a>
    <a class="nav-link waves-light" *ngIf="authenticated" mdbRippleRadius (click)="logout()"><i class="fa fa-user"></i> <span class="clearfix d-none d-sm-inline-block">Log Out</span></a>
  </li>

文档说要使用auth.isAuthenticated()来调用服务中的函数

  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // access token's expiry time
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

我想也许我应该将this.authenticated = this.authService.isAuthenticated()添加到标题组件中每个login()/logout()函数的末尾,但我觉得我用这个方向走错了方向

欢迎任何输入。

更新

修改logout()以调用this.authenticated = this.authService.isAuthenticated()确实解决了问题,但在刷新页面之前,Login仍然没有注销。

2 个答案:

答案 0 :(得分:5)

您可以将authenticated写为属性getter:

public get authenticated(): boolean {
    return this.authService.isAuthenticated();
}

答案 1 :(得分:0)

从我可以看到你只是在init上更新你的变量。这就是你刷新时只看到变化的原因。如果你这样做

login() {
this.authService.login();
this.authenticated = this.authService.isAuthenticated()
  }

在登录方法中它应该可以工作。