2016-05-13 52 views
2

某些用戶通過邀請進入我的web應用程序。所以他們會有一個類似如下的鏈接:https://example.com/invitaion/12345其中12345是他們唯一的邀請號碼。Angular 2 RC1:從使用的初始URL獲取參數

當用戶點擊鏈接,並且我的AppComponent在客戶端被框架初始化時,我如何得到使用的URL是「invitation/*」的事實,以及如何獲得邀請號?

回答

0

你會想要使用RouteParams來訪問該變量,並在你的組件中使用它。

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

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

現在組件本身內:在AppComponent

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

如果這不起作用,可能需要嘗試從'@ angular/router-deprecated'導入RouteParams,請告訴我! –

2

在新路由器(> = RC.0)這可以用

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

進行(以得到第二段)

MyComponent這很容易:

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