服务数据变化时自动刷新导航栏

Automatically refresh navbar when service data changes

我正在尝试制作一个登录-注销导航栏,它只在有用户登录时显示注销按钮,只有在没有用户登录时才显示登录按钮。我是使用 firebase auth 服务及其功能之一检测是否有用户登录。我通过在我希望它检查的每个按钮上放置一个 *ngIf 来实现这一点,如下所示:

<a *ngIf="!_auth.userData" routerLink="/auth/login" class="login active">Login</a>
<a *ngIf="!_auth.userData" routerLink="/auth/register" class="register active">Register</a>
<a *ngIf="_auth.userData" routerLink="/landing" class="landing active">Landing</a>
<div class="divider anchor active">|</div>
<li class="profile anchor active">Profile</li>
<li class="paginator anchor active">Paginator</li>
<li class="search anchor active">Search</li>
<li class="ng-content anchor active">NgContent</li>
<li class="footer anchor active">Footer</li>
<div class="divider anchor active">|</div>
<a *ngIf="_auth.userData" (click)="_auth.SignOut()" class="logout active">Logout</a>
<a *ngIf="!_auth.userData" routerLink="/auth/forgot" class="forgot active">Forgot Password</a>

实际登录在登录组件内部,并具有下一个代码:

<button [disabled]="loginForm.invalid" class="button" type="submit" (click)="_auth.SignIn(userEmail.value, userPassword.value)">Login</button>

*ngIf检测_auth.userData的状态,当没有用户登录时此函数returns null。

    /* Saving user data in localstorage when 
    logged in and setting up null when logged out */
    this._afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user')!);
      } else {
        localStorage.setItem('user', "");
        JSON.parse(localStorage.getItem('user')!);
      }
    })
  }

它工作正常,但我必须在每次登录或注销时手动刷新页面,以便导航栏刷新。如何让它在用户登录或注销时自动刷新?

因此您的 userData 保存当前用户值,并且您无法在模板中检测到该更改。我会做的是:

// assuming it's an auth service, I'd do something like this: set the value of the login state in your public service property based on the localstorage value
isLoggedIn$ = new BehaviorSubject(!!localStorage.getItem('user'));

// service call when logging in - change the state of the isLoggedIn$
this._afAuth.authState.subscribe(user => {
  if (user) {
    this.userData = user;
    localStorage.setItem('user', JSON.stringify(this.userData));
    JSON.parse(localStorage.getItem('user') || "{}");
    this.isLoggedIn$.next(true);
  } else {
    localStorage.removeItem('user');
    JSON.parse(localStorage.getItem('user') || "{}");
    this.isLoggedIn$.next(false);
  }
})

// and in the template file
<a *ngIf="!(_auth.isLoggedIn$ | async)" routerLink="/auth/login" class="login active">Login</a>
<a *ngIf="_auth.isLoggedIn$ | async" routerLink="/auth/register" class="login active">register</a>