簡體   English   中英

服務數據變化時自動刷新導航欄

[英]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 的狀態,該函數在沒有用戶登錄時返回 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM