Passing params angular 2 traditional way

北战南征 提交于 2020-01-22 02:32:06

问题


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



来源:https://stackoverflow.com/questions/44331189/passing-params-angular-2-traditional-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!