Retrieving the active component and path

我的梦境 提交于 2019-12-07 07:23:42

问题


With Angular2, how would I retrieve the current active component and path?

For example I might have the following routes:

{ path: '', component: HomeComponent },
{ path: 'list', component: ListComponent },
{ path: ':id/', component: CustomComponent }

If I had navigated to https://domain.com/test is there a way to know I'm currently viewing the CustomComponent and to retrieve the id/path, which in this case is "test"?

I could use window.location.pathname with regex to get the path but this is messy and still doesn't allow me to easily get the active component.


回答1:


Yes you can check current active component using router snapshot-

import { Router,ActivatedRoute }      from '@angular/router';

constructor(public route : ActivatedRoute) {
    var snapshot = route.snapshot;
    console.log(snapshot._routeConfig.component.name); //This will give you the name of current active component
  }

Note- snapshot._routeConfig.component.name it will give you the active component name, and if you want url you can also get it by .url instead of name




回答2:


you can enable trace in your router config for root {enableTracing: true} to get more idea how routes are resolved and activated




回答3:


In ActivatedRouteSnapshot the component property is defined as being one of the following

component: Type<any> | string | null;

So you can't just do component.name unless you've already made sure you have Type<any>. This is because .name on a string doesn't exist.

Now Type<any> is actually a function that creates the type (your component type) and is defined as:

export interface Type<T> extends Function {
    new (...args: any[]): T;
}

So you can do something like this, which will actually compile

 if (typeof(this.route.snapshot.component) === 'function')
 {
     // the compiler is 'smart' enough to know that component here must be Type<T>
     const name = this.route.snapshot.component.name;
 }

An 'elegant' way to do it is using a typescript typeguard (although to be frank in this case it doesn't give you much of a benefit over what I just said).

isComponent(item: Type<any> | string | null): item is Type<any>
{
    return typeof item === 'function';
}

Then you can say this.name = isComponent(this.route.snapshot.component) ? this.route.snapshot.component : null.

Important: component.name is still valid in an AOT build, but unfortunately with --prod it will end up being something random like r.

I've resorted to having to inject private element: ElementRef<HTMLElement> and then look for the tag name. This will still be present even with an AOT prod build. There may be a performance cost to doing this so cache it if you're using it a lot.

    if (element.nativeElement.tagName.startsWith('RR-')){
        super.name = element.nativeElement.tagName;
    }



回答4:


Yah, the angular 2 starter guide covers all that, basically you need to inject ActivatedRoute on your component then you can retrieve the information you want by subscribing to the route params.

I would really recommend you to do the angular tutorial tour of heroes, it is actually pretty good learning material that they provided.

Inject ActivatedRoute, on your component constructor:

constructor(private route: ActivatedRoute) {
}

ngOnInit() {
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
  }



回答5:


Sure, using ActivatedRoutemodule you can access route parameters or bind to parameters cgange event

import {ActivatedRoute} from "@angular/router";

constructor(private activatedRoute: ActivatedRoute) { 
}

this.activatedRoute.params.subscribe(params => {
  console.log(params['id']);
});

Also here you can also access your current component type using

this.activatedRoute.component;


来源:https://stackoverflow.com/questions/41580495/retrieving-the-active-component-and-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!