0

I want to avoid user change the URL from /dashboard/1234-12 to /dashboard to prevent an error, so I want to redirect to /home when user type /dashboard without the id.

I have this route:

{
  path: 'dashboard/:id',
  component: DashboardComponent,
  canActivate: [CanActivateViaAuthGuard, CheckVidGuard],
},

And this CheckVidGuard:

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): boolean {
  const vid = route?.params?.vid;

  if (!vid) {
    this.router.navigate(['/home']);
    return false;
  }

  return true;
}

My Dashboard component only get this id and do some things:

ngOnInit() {
  this.id = this.activatedRoute.snapshot.paramMap?.get('id');
}

But every time I tried to go to /dashboard (without the id param) to get redirected to /home I got this error Error: NG04002: Cannot match any routes. URL Segment: 'dashboard'

I know that there is no route defined without the id but the guard seems to not work.

I tried adding this route and it works, but I don't want to add other route for this.

{
  path: 'dashboard',
  component: DashboardComponent,
  canActivate: [CanActivateViaAuthGuard],
},

With a Resolver the result is the same, don't work:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): string {
  const vid = route.params['vid'];
  if (!vid) {
    this.router.navigate(['/home/dashboard']);
    return null;
  }
  return vid;
}
jgcarrillo
  • 148
  • 11

2 Answers2

1

According to https://angular.io/guide/router#route-order

You could just add a dashboard route after the dashboard/{id} route with a rediract to home.

Or have a wildcard route at the and of the config to redirect to home

Ivan Tarskich
  • 1,332
  • 1
  • 12
  • 19
  • Yeah! That's work as I said but... is this a real solution better than use a guard or a resolver? May I have to create redirects for every route I want to control? – jgcarrillo Feb 16 '23 at 12:02
  • well wildcard routes are the solution for invalid routes..so why not use it. you can maybe check for the previous url to provide custom logic on redirect. + i dont think your route is called could you verify this – Ivan Tarskich Feb 16 '23 at 12:49
  • I finally have implemented the solution with **wildcard**, not sure if it is the correct one but it works. – jgcarrillo Feb 17 '23 at 13:12
0

As Ivan Tarskich said, I have finally implemented the wildcard solution using this generic route:

{
  path: '**',
  redirectTo: '/home',
},

Not sure if it is the more appropriate solution but it works.

jgcarrillo
  • 148
  • 11