i'm trying to make guard, but i cant return value after subscribe
This code returns error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
I checked some solutions and they using map
instead of subscribe
, but i'm getting this error TS2339: Property 'map' does not exist on type 'Observable '.
guard code
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private auth:AuthService, private router:Router) {
}
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>{
if (!this.auth.isAuth) {
if (!localStorage.getItem('token')){
this.router.navigate(['/login'])
return of(false);
}
this.auth.checkAuth().subscribe(
(data) => {
if (this.auth.isAuth){
return of(true)
} else {
this.router.navigate(['/login'])
return of(false)
}
}
)
}else {
return of(true);
}
}
canActivateChild(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>{
return this.canActivate(route, state)
}
}
checkAuth code
checkAuth():Observable<UserDto>{
return this.http.get<UserDto>(`/api/user/refresh`, {withCredentials:true, observe:'body', responseType:'json'})
.pipe(
tap(
(data) => {
localStorage.setItem('token', data.accessToken)
this.setAuth(true)
this.setUser(data.user)
},
(error) => {
console.log(error)
}
)
)
}
CodePudding user response:
First of all, you code shows wrong usage for the RxJS and angular
Second, convert you subacribe to map, ie instead
this.auth.checkAuth().subscribe( (data) => { if (this.auth.isAuth){ return of(true) } else { this.router.navigate(['/login']) return of(false) } } )
Write (notice return before, that's the reason for your error)
return this.auth.checkAuth().pipe(
map(data => {
if (this.auth.isAuth){
return true;
} else {
this.router.navigate(['/login'])
return false;
}
}
):