I am currently developing an angular app using its router functionality. All routes seem to have been working well until I found out that after a successful login, the url path I've set it to, which is '/admin' will not be followed and the router instead defaults to a '/'. This is the code:
//login.component.ts
if (this.authService.getUserRole() == 'user' || 'agent') {
window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
window.location.assign('/admin')
}
//app.routing.ts
import {AdminComponent} from './admin-master/admin/admin.component;
import {HomeComponent} from './home/home.component;
const appRoutes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: {permission:{only: ['admin']}}}
]
EDIT: (added auth.guard.ts)
//auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const permission = next.data["permission"];
if(this.authService.isLoggedIn() &&
permission.only.includes(this.authService.getUserRole())) {
return true;
} else {
this.router.navigateByUrl('/logout');
}
}
}
The Problem:
Although a successful login has been done, the router will redirect a user to a blank url instead of the set URL I have provided specifically in the
login.component.tsfolder.Because it will redirect to an empty URL, elements from the
home.component.htmlwill also display within my admin dashboard which I don't want to happen.
In conclusion, how do I route the following functions correctly? Am I doing something wrong? Thanks for the help!
NavigationStart(id: 1, url: '/')AuthGuardlooks like ? Also your routing looks a little strange to me, you're not using the angular build in routing functionality (angular.io/guide/router) Instead ofwindow.location.assign('/admin')you should usethis.router.navigate(['admin'], { relativeTo: this.route });window.location.assignis to trick the browser into thinking that I've already redirected to the route. This is due to some of my functionalities only loading if I refresh the application.