简体   繁体   English

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

[英]How to retrieve last URL segment name in Angular 2 RC1 Router

I have an Angular2 router (RC1) that loads the same component in all of its three routes: 我有一个Angular2路由器(RC1),它在所有三个路由中都加载相同的组件:

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

The reason behind this is because I need three forms for CRUD actions that very similar to each other. 这背后的原因是因为我需要三种非常相似的CRUD动作形式。 So, I decided to use the same component combined with a few *ngIf s based on the component mode (create, detail, update). 因此,我决定基于组件模式(创建,详细信息,更新),将同一组件与几个*ngIf结合使用。

The problem now is that I can't find a way to get the name of the last segment on the URL. 现在的问题是,我找不到一种方法来获取URL上最后一个段的名称。 Ideally I could like to do something like this (pseudocode): 理想情况下,我想做这样的事情(伪代码):

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

How can I achieve such functionality? 我如何实现这种功能? Any ideas? 有任何想法吗? Thank you! 谢谢!

I accomplished something similar 我完成了类似的事情

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

See also https://stackoverflow.com/a/37230716/217408 or https://stackoverflow.com/a/37230758/217408 另请参阅https://stackoverflow.com/a/372​​30716/217408https://stackoverflow.com/a/372​​30758/217408

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM