2

Some users enter my web app via invitations. so they would have a link that looks something like this: https://example.com/invitaion/12345 where 12345 is their unique invitation number.

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
JasonGenX
  • 4,952
  • 27
  • 106
  • 198

2 Answers2

2

In the new router (>= RC.0) in the 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 2nd segment)

In MyComponent this is easier:

routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
  this.id = curr.getParam('id');
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

You'll want to use RouteParams to access that variable, and use it within your Component.

// let's assume you labeled it as `path : '/invitation/:id'` in your @Route setup.

@Route([
    { path : '/invitation/:id', component : MyComponent }
]) 

Now within 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');
    }
}
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
  • You might need to try importing RouteParams from `@angular/router-deprecated` if that doesn't work, let me know! – Mark Pieszak - Trilon.io May 13 '16 at 20:54
  • I know this is an old reponse but the import isn't working for me : `Module ../../../../../node_modules/@angular/router/router"' has no exported member 'RouteParams'.ts(2305) ` same for `@angular/router-deprecated` – Boris BELLOC Jul 22 '20 at 09:00