I have a CanActivate guard that is checking if the user is logged in, if they are, return true and navigates to localhost:4200/ otherwise it navigates to /login but also keeps the current query params as I'm coming from an external page. However on returning true, all the query params are removed, how can I preserve these?
This is the code below:
import { Injectable } from "@angular/core";
import {
ActivatedRoute,
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
} from "@angular/router";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { UserService } from "../user/user.service";
@Injectable()
export class RedirectLoginGuard implements CanActivate {
constructor(
private userService: UserService,
private router: Router,
private route: ActivatedRoute
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.isLoggedIn(route, state);
}
isLoggedIn(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.userService.userProfile$.pipe(
map((response) => {
if (response) {
//here on return true, my query params aren't kept and it just resolves to localhost:4200 instead of localhost:4200?userid=34424 etc.
return true;
} else {
this.router.navigate(["/login"], {
queryParams: route.queryParams,
});
return false;
}
})
);
}
}