某些用户通过邀请进入我的web应用程序。所以他们会有一个类似如下的链接:https://example.com/invitaion/12345
其中12345是他们唯一的邀请号码。Angular 2 RC1:从使用的初始URL获取参数
当用户点击链接,并且我的AppComponent在客户端被框架初始化时,我如何得到使用的URL是“invitation/*”的事实,以及如何获得邀请号?
某些用户通过邀请进入我的web应用程序。所以他们会有一个类似如下的链接:https://example.com/invitaion/12345
其中12345是他们唯一的邀请号码。Angular 2 RC1:从使用的初始URL获取参数
当用户点击链接,并且我的AppComponent在客户端被框架初始化时,我如何得到使用的URL是“invitation/*”的事实,以及如何获得邀请号?
你会想要使用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');
}
}
在新路由器(> = 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');
}
如果这不起作用,可能需要尝试从'@ angular/router-deprecated'导入RouteParams,请告诉我! –