Angular 2 RC1: Get Parameters from Source URL

Some users enter my web application using prompts. so they will have a link that looks something like this: https://example.com/invitaion/12345 where 12345 is their unique invitation number.

When users click on a link and my AppComponent is initialized on the client side with the framework, how can I get the fact that the URL was "invitation / *" and how can I get the invitation number?

+2
angular
source share
2 answers

You want to use RouteParams to access this variable and use it in your component.

 // let assume you labeled it as `path : '/invitation/:id'` in your @Route setup. @Route([ { path : '/invitation/:id', component : MyComponent } ]) 

Now in the component itself:

 import { RouteParams } from '@angular/router'; // Now simply get the ID when injecting RouteParams within your constructor class MyComponent { id: string; constructor(_params: RouteParams) { this.id = _params.get('id'); } } 
0
source share

In the new router ( > = RC.0 ) in AppComponent this can be done with

  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); }); } 

(to get the second segment)

In MyComponent this is simpler:

 routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void { this.id = curr.getParam('id'); } 
+2
source share