I have a couple of buttons that I want to display only if user is logged in. My problem is that simple *ngIf is not working like I want it to. For example I have this button Add Recipe:
<div class="background">
<button type="button" *ngIf="isUserAuthenticated" class="btn btn-primary float-right m-2" data-bs-toggle="modal" data-bs-target="#exampleModal"
(click)="addClick()"
data-backdrop="static"
data-keyboard="false">
Add Coffee
</button>
It is button for showing modal. I want that button to be displayed only if user is authenticated. This is how my .ts looks like:
export class RecipeDetailsComponent implements OnInit {
...
public isUserAuthenticated: boolean = false;
ngOnInit(): void {
this.userService.authChanged
.subscribe(res => {
this.isUserAuthenticated = res;
})
}
and my userService methods for checking if authenticated:
export class UserService {
private _authChangeSub = new Subject<boolean>()
public authChanged = this._authChangeSub.asObservable();
public sendAuthStateChangeNotification = (isAuthenticated: boolean) => {
this._authChangeSub.next(isAuthenticated);
}
public isUserAuthenticated = (): boolean => {
const token = localStorage.getItem("token");
return token != null && this._jwtHelper.isTokenExpired(token) == false;
}
Button appears only If i set isUserAuthenticated = true when declaring and hides if it false. I guess button reads isUserAthenticated property and show it selfs before ngOnInit. How can I delay button display till ngOnInit is resolved or just refresh after that?
CodePudding user response:
If I understand your question, You're having trouble because of timing. Your code doesn't include when or how the value changes but I am guessing that the value is changed before your component initializes and therefore you are subscribing late?
If so, I recommend changing
private _authChangeSub = new Subject<boolean>()
to
private _authChangeSub = new ReplaySubject<boolean>(1);
This way, even when subscribing after the value has been emitted, the component will still receive the value. See https://www.learnrxjs.io/learn-rxjs/subjects/replaysubject