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

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

问题描述

> Angular2在Router-Outlet之外获取路由器参数类似的问题,但定位到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对象只允许我访问原始网址,而不是其解析版本。我可以使用路由器的parseUrl方法进行解析,但是这种格式并不是特别有用,并且会很脆弱,所以我宁愿不使用它。在路由事件中,我也查看了router的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?

推荐答案

如果有人在寻找这个问题的最新解决方案(角度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-angular-service-1965afe1470e

显然,您可以

    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.

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

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