Angular 2 RC1: Get parameters from the initial URL used

后端 未结 2 677
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 16:19

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 thei

相关标签:
2条回答
  • 2021-01-15 17:20

    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');
        }
    }
    
    0 讨论(0)
  • 2021-01-15 17:21

    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');
    }
    
    0 讨论(0)
提交回复
热议问题