简体   繁体   中英

Angular 2 : Routing with different types of slugs

In my component I have list of menu items. One consist of post other of pages.

menu.component.ts

selectedPost(postslug){
  console.log('post slg ', postslug);
    this._router.navigate([postslug]);
}

selectedPage(pageslug){
  console.log('page slg ', pageslug);
    this._router.navigate([pageslug]);
}

app.routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: PostListComponent,
    pathMatch: 'full'
  }

  ,
  {
       path: ':postslug',  // This is for the posts 
      component: PostSingleComponent,
  }
    ,
  {
     path: ':pageslug',
     component: PageSingleComponent  // This is for the pages 
  }


];

As I understood that because of custom slug that I pass it should pick up and load the correct component. But it load the first one that has ': + something'.

Is there a way around this ?

If there isn't is there a way to push via the function a custom category, and in the routing to redirect to the category?

For example in the function:

  selectedPost(catName, postslug){
      console.log('post slg ', postslug);
        this._router.navigate([catName, postslug]);
    }

And in the routing I would have:

const routes: Routes = [
  {
    path: '',
    component: PostListComponent,
    pathMatch: 'full'
  }

  ,
  {
       path: 'catName/:postslug',  // This is for the posts 
      component: PostSingleComponent,
  }
    ,
  {
     path: ':pageslug',
     component: PageSingleComponent  // This is for the pages 
  }


];

try below,

const routes: Routes = [
  {
    path: '',
    component: PostListComponent,
    pathMatch: 'full'
  }

  ,
  {
       path: 'posts/:postslug',  // This is for the posts 
      component: PostSingleComponent,
  }
    ,
  {
     path: 'pages/:pageslug',
     component: PageSingleComponent  // This is for the pages 
  }
];

and on click,

selectedPost(postslug){
  console.log('post slg ', postslug);
    this._router.navigate(['posts',postslug]);
}

selectedPage(pageslug){
  console.log('page slg ', pageslug);
    this._router.navigate(['pages',pageslug]);
}

Check documentation on How Routing works here. , it explains in detail about Routing and Navigation.

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM