Angular 2:如何从路由器插座外部获取路线的参数 [英] Angular 2: How do I get params of a route from outside of a router-outlet

查看:22
本文介绍了Angular 2:如何从路由器插座外部获取路线的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular2 在路由器出口外获取路由器参数的类似问题 但针对的是 Angular 2 的发布版本(因此是路由器的 3.0.0 版).我有一个带有联系人列表和路由器插座的应用程序,可以显示或编辑所选联系人.我想确保在任何时候(包括页面加载时)都选择了正确的联系人,因此我希望能够在更改路线时从路线中读取id"参数.

Similar question to Angular2 Get router params outside of router-outlet but targeting the release version of Angular 2 (so version 3.0.0 of the router). I have an app with a list of contacts and a router outlet to either display or edit the selected contact. I want to make sure the proper contact is selected at any point (including on page load), so I would like to be able to read the "id" param from the route whenever the route is changed.

我可以通过订阅路由器的 events 属性来处理路由事件,但是 Event 对象只是让我访问原始 url,而不是它的解析版本.我可以使用路由器的 parseUrl 方法解析它,但是它的格式并不是特别有用,而且会很脆弱,所以我宁愿不使用它.我还查看了路由事件中路由器的 routerState 属性,但 params 在快照中始终是一个空对象.

I can get my hands on routing events by subscribing to the router's events property, but the Event object just gives me access to the raw url, not a parsed version of it. I can parse that using the router's parseUrl method, but the format of this isn't particularly helpful and would be rather brittle, so I'd rather not use it. I've also looked all though the router's routerState property in the routing events, but params is always an empty object in the snapshot.

有没有一种我刚刚错过的实际直接的方法来做到这一点?我是否必须将联系人列表包装在永远不会改变的路由器插座中才能使其正常工作,或类似的东西?

Is there an actual straight forward way to do this that I've just missed? Would I have to wrap the contact list in a router-outlet that never changes to get this to work, or something like that?

推荐答案

如果有人正在寻找此问题的最新解决方案(angular 8),我偶然发现了这篇对我来说非常有效的文章.

If any body was looking for the latest solution of this issue (angular 8) I stumbled upon this article which worked very well for me.

https://medium.com/@eng.ohadb/how-to-get-route-path-parameters-in-an-angular-service-1965afe1470e

显然,您可以直接在路由器插座外的组件中执行相同的实现,它仍然可以工作.

Obviously you can do the same implementation straight in a component outside the router outlet and it should still work.

    export class MyParamsAwareService {
  constructor(private router: Router) { 
    this.router.events
      .pipe(
        filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
        map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
      )
      .subscribe(params => {
      console.log(params);
      // Do whatever you want here!!!!
      });
  }

希望能避免我经历的同样的挣扎.

In the hope to spare the same struggle I went through.

这篇关于Angular 2:如何从路由器插座外部获取路线的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆