I have an Angular app.
- On the app init we should show redirecting spinner (user is not logged in)
- When the user is logged in, then we should show content
I've done it as below: HTML:
<div *ngIf="(isLoggedIn$ | async); else loading">
<!-- some other content -->
<router-outlet></router-outlet>
</div>
<ng-template #loading>
<app-spinner text="Redirecting..."></app-spinner>
</ng-template>
TS:
isLoggedIn$: Observable<boolean>;
constructor(private authService: AuthService) {}
ngOnInit() {
this.isLoggedIn$ = this.authService.isLoggedIn();
}
It works well on the app init. When the user is logged in, I still see the redirection spinner. I have to refresh the window to see the router-outlet content.
My temporary workaround is to put <router-outlet> inside <ng-template #loading>, eg:
<ng-template #loading>
<app-spinner text="Redirecting..."></app-spinner>
<router-outlet></router-outlet> <!-- HERE workaround -->
</ng-template>
But don't want to use this workaround permanently as I want to fix this Observable problem - as I mentioned it is not refreshed even when the console.log() says that I'm logged in.
Here is my Auth Service:
@Injectable({
providedIn: 'root'
})
export class AuthService {
manager: UserManager = new UserManager(environment.settings);
constructor() {
}
getUser(): Observable<User> {
return from(this.manager.getUser());
}
isLoggedIn(): Observable<boolean> {
return this.getUser()
.pipe(
map(user => {
return user != null && !user.expired;
})
);
}
startAuthentication(): Promise<void> {
return this.manager.signinRedirect();
}
completeAuthentication(): Observable<User> {
return from(this.manager.signinRedirectCallback());
}
async signOut() {
await this.manager.signoutRedirect();
}
}
Of course, I am using CanActivate as well.
this.authService.isLoggedIn?<router-outlet>because the router can not active a route. This has nothing to do with theisLoggedIn$observable.tapit withconsole.logto check.