Thomas W.
Thomas W.

Reputation: 2224

Define Angular routes to redirect depending on route parameters

I've a very simple Angular routing module which is used to redirect from one route to another one:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'foo',
    redirectTo: 'bar',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class FooRoutingModule { }

Now, I want to change the redirection so that it depends on one route parameter (there may be more parameters than this one). So, foo?para=0 should redirect to barA, and foo?para=1 should redirect to barB. What is the simplest way to achieve this?

Upvotes: 1

Views: 2245

Answers (1)

JeanPaul A.
JeanPaul A.

Reputation: 3724

You can use Guards to manipulate routing.

In your case a CanActivate guard should do the job well. Read more about them here : https://angular.io/guide/router#canactivate-requiring-authentication

@Injectable()
export class MyGuard implements CanActivate {

  constructor(public router: Router) {}

  canActivate(route: ActivatedRouteSnapshot) {
   switch(route.queryParams['para']) {
     case '0' :
        this.router.navigate(['my/url]);
        break;
     case '1':
          ....
    }
    return false;
  }
}

The "return false;" is very important in your routing, so that the current navigation ( in your case to 'foo') is cancelled.

And in your routing

const routes: Routes = [
  {
    path: 'foo', canActivate:[ MyGuard ]
  }
];

Upvotes: 3

Related Questions