Angular 2:如何从router-outlet外部获取路由的参数?

Angular 2: How do I get params of a route from outside of a router-outlet

本文关键字:路由 获取 参数 外部 router-outlet Angular      更新时间:2023-09-26

与Angular2类似的问题,在router-outlet之外获取路由器参数,但目标是Angular2的发布版本(即路由器的3.0.0版本)。我有一个应用程序与联系人列表和路由器出口显示或编辑所选的联系人。我要确保在任何时候(包括在页面加载)都选择适当的联系人,所以我希望能够在路由更改时从路由读取"id"参数。

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

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

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

https://medium.com/@eng.ohadb -如何-路由路径参数-在-一-角-服务- 1965 afe1470e

显然,你可以直接在路由器出口外的组件中做同样的实现,它应该仍然可以工作。

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

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

我一整天都在努力解决这个问题,但我想我终于找到了一种方法,通过监听一个路由器事件来解决这个问题。准备好吧,这有点棘手(很难看?),但到目前为止,它是可以工作的,至少在最新版本的Angular (4.x)和Angular Router (4.x)上是这样。如果他们更改了某些内容,这段代码将来可能无法工作。

基本上,我找到了一种方法来获得路由的路径,然后自己重建一个自定义参数映射。

在这里:

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
@Component({
  selector: 'outside-router-outlet',
  templateUrl: './outside-router-outlet.component.html',
  styleUrls: ['./outside-router-outlet.component.css']
})
export class OutSideRouterOutletComponent implements OnInit {
  path: string;
  routeParams: any = {};
  constructor(private router: Router) { }
  ngOnInit() {
    this.router.events.subscribe(routerEvent => {
      if (routerEvent instanceof RoutesRecognized) {
          this.path = routerEvent.state.root['_routerState']['_root'].children[0].value['_routeConfig'].path;
          this.buildRouteParams(routerEvent);
      }
    });
  } 
  buildRouteParams(routesRecognized: RoutesRecognized) {
    let paramsKey = {};
    let splittedPath = this.path.split('/');
    splittedPath.forEach((value: string, idx: number, arr: Array<string>) => {
      // Checking if the chunk is starting with ':', if yes, we suppose it's a parameter
      if (value.indexOf(':') === 0) {
        // Attributing each parameters at the index where they were found in the path
        paramsKey[idx] = value;
      }
    });
    this.routeParams = {};
    let splittedUrl = routesRecognized.url.split('/');
    /**
     * Removing empty chunks from the url,
     * because we're splitting the string with '/', and the url starts with a '/')
     */
    splittedUrl = splittedUrl.filter(n => n !== "");
    for (let idx in paramsKey) {
      this.routeParams[paramsKey[idx]] = splittedUrl[idx];
    }
    // So here you now have an object with your parameters and their values
    console.log(this.routeParams);
  }
}