dev_054
dev_054

Reputation: 3718

Set default query params while routing

I've the following route config:

const routes: Routes = [
  // another routes
  { component: UsersListComponent, path: 'users' }
];

I want to "automatically" include some default QUERY parameters when something route to this.

E.g.:

The route /users become /users?p=1s&15, when it has NO query parameters.

I just got stucked trying to do it with guards (I'm not even sure that's the best choice for do this). Below is a piece of my actual code:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    // Just for make it clear:

    if (state.url === '/users') {
      this.router.navigate([], {
        queryParams: {
          p: 1,
          s: 15
        },
        relativeTo: this.activatedRoute
      });
    }

    return true;
  }
}

Stacbklitz link

Upvotes: 3

Views: 3091

Answers (1)

terahertz
terahertz

Reputation: 3491

You're missing a return false in your canActivate() guard. Also, this.router.navigate([]) navigates you to your current route, which can be /my-default-page, etc. Hence, it navigated you to /my-default-page?p=1&s=15. It wasn't navigating you to your next route with query params, /users?p=1&s=15.

However, because the canActivate() guard always returned true, you were still navigated to /users.

To fix this:

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      console.log('state', state.url)
    if (state.url === '/users') {
      console.log("true");
      this.router.navigate([state.url], { //need to change this to state.url, which is your next route 
        queryParams: {
          p: 1,
          s: 15
        },
        relativeTo: this.activatedRoute
      });
      return false; //you're missing this
    }

    return true;
  }

Also, since your use case requires /users without query parameters to always be routed to /users?p=1&s=15, you should shift your canActivate:[myAuthGuard to the users route.

E.g.

... //other routes

{
  path: 'users',
  canActivate: [MyAuthGuard],
  component: MyComponent,
  runGuardsAndResolvers: "always" //add this to always trigger AuthGuard
},

...

forked stackblitz

Upvotes: 3

Related Questions