简体   繁体   中英

How to retrieve last URL segment name in Angular 2 RC1 Router

I have an Angular2 router (RC1) that loads the same component in all of its three routes:

@Routes([
  { path: '/create',     component: MyComponent },
  { path: '/detail/:id', component: MyComponent },
  { path: '/update/:id', component: MyComponent },
])

The reason behind this is because I need three forms for CRUD actions that very similar to each other. So, I decided to use the same component combined with a few *ngIf s based on the component mode (create, detail, update).

The problem now is that I can't find a way to get the name of the last segment on the URL. Ideally I could like to do something like this (pseudocode):

export class MyComponent {
  constructor(private router: Router) {
    this.mode = this.router.getLastURLSegmentName();
    if (this.mode == 'detail' or this.mode == 'update') {
      let param_id = this.router.getLastURLSegment().getParam('id');
    }
  }
}

How can I achieve such functionality? Any ideas? Thank you!

I accomplished something similar

import 'rxjs/add/operator/first';
...

constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
  router.changes.first().subscribe(() => {

    let urlTree = this.routeSerializer.parse(location.path());
      console.log('id', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
  });
}

See also https://stackoverflow.com/a/37230716/217408 or https://stackoverflow.com/a/37230758/217408

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