最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin7浏览0评论

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?

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?

Share Improve this question edited May 23, 2017 at 10:30 CommunityBot 11 silver badge asked Oct 3, 2016 at 16:52 IxonalIxonal 6568 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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./@eng.ohadb/how-to-get-route-path-parameters-in-an-angular-service-1965afe1470e

Obviously you can do the same implementation straight in a ponent 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.

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.ponent.html',
  styleUrls: ['./outside-router-outlet.ponent.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);
  }
}
发布评论

评论列表(0)

  1. 暂无评论