Reputation: 681
i am trying to return a true or false within an promise(gameid) inside an observable that returns me if the user is logged in or not:
here my authguard:
//Angular
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
//Rxjs
import { Observable } from 'rxjs';
import { map, take, mergeMap } from 'rxjs/operators';
//Services
import { LoginService } from '../services/login.service';
@Injectable()
export class AuthGuard implements CanActivate{
constructor(
public router: Router,
public loginService: LoginService
){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.loginService.getAuthenticated().pipe(map(user => {
if(user && user.hasOwnProperty('uid') && user.uid != "" ) {
this.loginService.getGameIdUser().then( game => {
if(game.hasOwnProperty["gameid"] && game.gameid != "") {
return true; // <-- this return is reached but doesnt effect my route
} else {
this.router.navigate(['selgame']);
return false;
}
})
} else {
this.router.navigate(['login']);
return false;
}
}))
}
}
it seems the return true does not effect the authguard.. where is my mistake?
Upvotes: 1
Views: 882
Reputation: 2171
Try something like this. You'll turn your promise into an observable.
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
public router: Router,
public loginService: LoginService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.loginService.getAuthenticated().pipe(concatMap((user) => {
if (user && user.hasOwnProperty("uid") && user.uid != "") {
return from(this.loginService.getGameIdUser()).pipe( // <-- Turn your promise to an observable
map((game) => {
if (game.hasOwnProperty.gameid && game.gameid != "") {
return true; // <-- this return is reached but doesnt effect my route
} else {
this.router.navigate(["selgame"]);
return false;
}
}),
);
} else {
this.router.navigate(["login"]);
return of(false);
}
}));
}
}
https://www.learnrxjs.io/learn-rxjs/operators/transformation/concatmap
https://www.learnrxjs.io/learn-rxjs/operators/creation/from
Upvotes: 2