Angular2 Get router params outside of router-outlet

后端 未结 5 1333
不思量自难忘°
不思量自难忘° 2021-01-04 14:26

I have a dashboard application which consists of a treeview component (which lists various content nodes) and a dashboard-edit component which renders some editable content

5条回答
  •  不知归路
    2021-01-04 14:35

    Get the active route from outside a component in angular 2.1.0 and Router 3.1.0

    I found a nice way to get all params, queryParmas, segments and fragments from the displayed route from anywhere inside your App. Just add this Code to any Component where you need it, or create a Service that can be injected throughout your App.

    import { Router, NavigationEnd } from "@angular/router";
    import { Component, OnInit } from '@angular/core';
    
    ...
    
    export class MyComponentOrService implements OnInit {
    
    constructor(private router: Router) {}
    
    ngOnInit() {
    
      /* this subscription will fire always when the url changes */
      this.router.events.subscribe(val=> {
    
        /* the router will fire multiple events */
        /* we only want to react if it's the final active route */
        if (val instanceof NavigationEnd) {
    
         /* the variable curUrlTree holds all params, queryParams, segments and fragments from the current (active) route */
         let curUrlTree = this.router.parseUrl(this.router.url);
         console.info(curUrlTree);
        }
      });
    }
    ...
    

提交回复
热议问题