Passing params angular 2 traditional way

2019-03-04 09:02发布

问题:

I am trying to pass parameters to one component in this format www.domain.com?param=value, but Angular keep sending parameters like this www.domain.com;param=value. Why replace ? for ;?

This is my route conf:

const router: Routes = [
    {path: '', redirectTo: '/shops', pathMatch: 'full'},
    {path: 'shops', component: ShopComponent, canActivate: [AuthManager]},
    {path: 'shop/new', component: NewShopComponent, canActivate: [AuthManager]},
    {path: 'shop/new/:id', component: NewShopComponent, canActivate: [AuthManager]},
    {path: 'login', component: LoginComponent},
    {path: 'register', component: RegisterComponent},
    {path: '**', component: ShopComponent}
];

and this how I pass the values

this._router.navigate(['shops', {id: id}]);

if I pass it like

this._router.navigate(['shops?id=id']); 

i get undefined route error.

回答1:

Angular provides three types of parameters:

  • Required parameters
  • Optional parameters
  • Query parameters

The look of the URL and the syntax for navigating using the parameters is different depending on which type of parameter you want to use.

If you want to use the "?" style, then you want the query parameters.

Query Parameters:

  • Are NOT included in the route path configuration. So if you want query parameters, do NOT add the :id to the path.

NOT this:

{path: 'shop/new/:id', component: NewShopComponent, canActivate: [AuthManager]},

RATHER this:

{path: 'shop/new', component: NewShopComponent, canActivate: [AuthManager]},

Then you navigate to the route like this:

this.router.navigate(['/shops'], 
   { 
    queryParams: { id: id }
   }
);

If you want more information on how to use routing ... check this out: https://app.pluralsight.com/library/courses/angular-routing/table-of-contents