Angular 2: How do I get params of a route from out

2019-04-07 17:27发布

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.

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?

1条回答
孤傲高冷的网名
2楼-- · 2019-04-07 17:41

I've been struggling with this issue for the whole day, but I think I finally figured out a way on how to do this by listening to one of the router event in particular. Be prepared, it's a little bit tricky (ugly ?), but as of today it's working, at least with the latest version of Angular (4.x) and Angular Router (4.x). This piece of code might not be working in the future if they change something.

Basically, I found a way to get the path of the route, and then to rebuild a custom parameters map by myself.

So here it is:

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);
  }
}
查看更多
登录 后发表回答