I have a AuthService class that has a simple BehaviorSubject, this is the start from my service:
private currentUserSubject: BehaviorSubject<UserModel> = new BehaviorSubject<UserModel>(undefined as any);
get currentUserValue(): UserModel {
return this.currentUserSubject.value;
}
set currentUserValue(user: UserModel) {
this.currentUserSubject.next(user);
}
And i have a function for testing
isLogged() {
return this.currentUserSubject.asObservable();
}
In a simple component that i have i make this:
isLoggedIn$!: Observable;
constructor(
public authService: AuthService,
private _bottomSheet: MatBottomSheet,
private modalService: NgbModal
) {}
ngOnInit(): void {
this.isLoggedIn$ = this.authService.isLogged();
}
And this is my front end from that component:
This works fine when i update this Behavior:
<div *ngIf="this.authService.isLogged() | async as _user; else noUser">
<ng-container *ngIf="_user">
<div> {{ _user.name }}</div>
</ng-container>
</div>
This don't:
<div *ngIf="this.isLoggedIn$ | async as _user; else noUser">
<ng-container *ngIf="_user">
<div> {{ _user.name }}</div>
</ng-container>
</div>
Why?
CodePudding user response:
this is normal because isLoggedIn$ contains only the initial value of the observable (isLogged ())
CodePudding user response:
I have created a stackblitz demo to try reproducing this issue and it works for me. You might have some other side-effect or typo in your app. Give it a try and check out if it works or missing anything from your code here:
https://stackblitz.com/edit/angular-stackoverflow-bs-no-issue?file=src/app/app.component.ts
I am going to share some tips with you about your code:
- You don't need to use
thisin the template - Service should be private (maybe you know it and did it just for the demo's sake)
- You don't need the extra ng-container -> ngIf inside the div, because the div already has the ngif condition.
