Reputation: 334
I have an Angular app.
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.
Upvotes: 1
Views: 1340
Reputation: 334
My solution is to add emitCompleted
method to AuthService
and calling it from AuthCallback
component.
AuthService:
private isLoggedInState = new BehaviorSubject<boolean>(false);
isLoggedIn(): Observable<boolean> {
return this.isLoggedInState.asObservable();
}
emitCompleted(user: User) {
this.isLoggedInState.next(user != null && !user.expired);
}
AuthCallback component:
export class AuthCallbackComponent implements OnInit {
constructor(
private authService: AuthService,
private router: Router
) { }
ngOnInit() {
this.authService.completeAuthentication()
.subscribe((result => {
this.authService.emitCompleted(result);
})
);
}
}
Upvotes: 1