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!

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick reply my friend! I tried this but I get the following error: (A) 'first' does not exist on type 'Observable<void>'. (B) Property 'path' does not exist on type 'Location'.
First is an operator and needs to be imported import 'rxjs/add/operator/first';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.