Reputation: 3791
I have Guard with canActivate
method:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.fireAuth.authState.pipe(
take(1),
map(authState => !!authState),
map(auth => !auth ? this.router.navigate(['/']) : true)
)
}
This is work, but I have typescript error in console:
ERROR in auth.guard.ts(20,7): error TS2322: Type 'Observable>' is not assignable to type 'boolean | UrlTree | Observable | Promise'.
How can I fix this?
Upvotes: 1
Views: 1971
Reputation: 691785
Don't use map()
. You don't want to change the emitted value. You just want to produce a side effect.
take(1),
map(authState => !!authState),
tap(auth => {
if (!auth) {
this.router.navigate(['/']);
}
});
Or, if it makes it simpler to understand to you:
take(1),
map(authState => {
if (authState) {
return true;
} else {
this.router.navigate(['/']);
return false;
}
});
Or better, return a UrlTree instead of navigating yourself when the router must navigate elsewhere:
take(1),
map(authState => !!authState || this.router.parseUrl('/'))
Upvotes: 1