如何在Angular 2 RC1路由器中检索最后一个URL段名称

时间:2016-06-02 13:31:46

标签: angular angular2-router

我有一个Angular2路由器(RC1),它在所有三个路由中加载相同的组件:

@Routes([
  { path: '/create',     component: MyComponent },
  { path: '/detail/:id', component: MyComponent },
  { path: '/update/:id', component: MyComponent },
])

这背后的原因是因为我需要三种形式的CRUD动作彼此非常相似。所以,我决定根据组件模式(创建,细节,更新)使用相同的组件和几个*ngIf

现在的问题是我无法找到获取URL上最后一段的名称的方法。理想情况下,我喜欢这样做(伪代码):

export class MyComponent {
  constructor(private router: Router) {
    this.mode = this.router.getLastURLSegmentName();
    if (this.mode == 'detail' or this.mode == 'update') {
      let param_id = this.router.getLastURLSegment().getParam('id');
    }
  }
}

我如何实现这样的功能?有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分: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);
  });
}

另请参阅https://stackoverflow.com/a/37230716/217408https://stackoverflow.com/a/37230758/217408