2
votes

In my AppComponent I am doing a startup check. If the application is opened with a query string that has a sessionId then we are good to go and I want to route them to the /application path. Otherwise I want them to navigate to the /create-session path. The problem is, the params subscription fires once before the app sees the query parameters which means the else statement is always triggered and the user is auto-redirected to the create-session path.

this.route.queryParams.subscribe(params => {
  if(params.sid) {
    this.ngRedux.dispatch(this.sessionActions.setSessionId(params.sid));
    this.router.navigate(['application'])
  }
  else{
    this.router.navigate(['create-session'])
  }
})

I tried doing something to filter out subscriptions without any data like this:

.first((val, idx, src)=> Object.keys(val).length > 0)

but then it won't trigger when there are no query params. Is there a way to get the immediate snapshot of the params without needing to subscribe to the ActivatedRoute?

note: this subscription is happening in ngOnInit

1

1 Answers

2
votes

You can achieve this functionality using guards in Angular.

Create a guard like this:

@Injectable()
export class SomeGuard implements CanActivate {
  constructor(
    private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot) {
      console.log('state params', state.root.queryParams);

      if (state.root.queryParams.sid){
        this.router.navigate(['application'])
      } else {
        this.router.navigate(['create-session'])
      }

      return false;
  }
}

Then add the guard to canActivate on the route where you want to execute this logic:

export const routes: Routes = [
  {
    path: '**',
    component: SomeComponent,
    canActivate: [SomeGuard]
  }
];

Don't forget to add the guard in your providers:

@NgModule({
  providers: [SomeGuard]
})