How to add query params to route in guard and pass it to component in Angular 4?

Viewed 1838

I am using a route guard in my angular 4 app, and I would like to add a query param to the route if a condition satisfies and return true.

Here's the code I have been working on

@Injectable()
export class ViewGuardService implements CanActivate {

  constructor(private router: Router) { }

  canActivate(activatedRoute: ActivatedRouteSnapshot, snapshot: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(!this.router.url.includes('/order-management')) {
      //ADD PARAMS TO ROUTE OR PASS DATA TO COMPONENT HERE AND THEN RETURN TRUE
       return true;
    } else {
       this.route.navigate['/login'];
       return false;
    }
  }
}

Usually, to navigate to a route with params we can use it as this.router.navigate(['/order-management', activatedRoute.url[0].path], { queryParams: { moveToOrders: true }});. But if I use this condition in the if condition, it turns out to an infinite loop of function calls.

So how do I pass params or data from the guard to the component? Please help me resolve this issue.

1 Answers

This is a bit hacky, but it works (Angular 11).

@Injectable({
  providedIn: 'root'
})
export class SetQueryParamGuard implements CanActivate {
  constructor(
    private _router: Router
  ) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> {
    const requiredQueryParam = route.queryParamMap.get('requiredQueryParam');

    // Query param is set, no further action
    if (requiredQueryParam) {
      return of(true);
    }

    return of(
               this._router
                   .parseUrl(state.url + `&requiredQueryParam=DEFAULT_VALUE`)
    );        
  }
}
Related