服务数据更改时自动刷新导航栏



我正在尝试制作一个登录-注销导航栏,它只在有用户登录时显示注销按钮,只在没有任何用户登录时才显示登录按钮。我使用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>

最新更新