2

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 *ngIfs 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!

AstrOne
  • 3,569
  • 7
  • 32
  • 54

1 Answers1

0

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for the quick reply my friend! I tried this but I get the following error: (A) 'first' does not exist on type 'Observable'. (B) Property 'path' does not exist on type 'Location'. – AstrOne Jun 02 '16 at 14:03
  • First is an operator and needs to be imported `import 'rxjs/add/operator/first';` – Günter Zöchbauer Jun 02 '16 at 14:06