【问题标题】:How to get the component name from current url?如何从当前 url 获取组件名称?
【发布时间】:2019-02-28 20:45:35
【问题描述】:

在 Angular SPA 中,我在标题组件中有一个按钮,在主组件中有一个路由器插座。我想要的是当我导航到另一个组件(例如:CustomerOverviewComponent)时,当前的url 是/customer/customer-overview。当我点击标题中的那个按钮时,我想调用CustomerOverviewComponent的方法。

main.component.html

<app-header></app-header>
<router-outlet name="page"></router-outlet>

header.component.html

<button (click)="doSomething()"></button>

header.component.ts

constructor(private router: Router, private activatedRouter: ActivatedRouter)
doSomething() {
  console.log(this.router.url); // if I navigate to customer overview, 
                                // will give me the result like this
                                // /customer/(page:customer-overview)

 console.log(this.activatedRouter.component); // this will print out
                                              // ƒ MainComponent(...){...}
}

我需要的是Header component里面,我想获取当前url的组件名。使用this.router.url 只会给我实际的url,我不知道如何从中获取组件名称。

使用this.activatedRouter.component 会给我ƒ MainComponent(...){...},我需要在CustomerOverviewComponent 中调用this.activatedRouter.component 来获得类似ƒ CustomerOverviewComponent(...){ 的东西。 ..}。

有什么方法可以在标题组件中获取CustomerOverviewComponent

【问题讨论】:

  • 在这里使用事件监听器..
  • 检查这个link & plunker
  • 你要获取组件类名吗?
  • @Chellappan 是的,确切的组件名称,如 CustomerOverviewComponent,然后从标题组件对每个组件内部具有相同名称的相同方法进行通用调用
  • 能否请您发布您定义的路由器代码,我认为使用路由器中的数据属性可以解决您的问题

标签: angular angular-routing


【解决方案1】:

您可以将 SubjectBehaviorSubject 用于相同目的

创建一个服务并在其中定义一个主题。

.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class AppCommonService {

theme = new BehaviorSubject<Number>(0);
toolbarTitle = new BehaviorSubject<String>('');


constructor() { }

}

订阅标题组件中的主题。

header.component.ts
export class HeaderComponent implements OnInit{
constructor(
 private appCommonService: AppCommonService)

 ngOnInit(){
  this.appCommonService.toolbarTitle.subscribe(data=>{
      console.log(data);
  })
 }

 doSomething(){
   //navigate to customer-overview component
 }
}

每当您导航到不同的组件时,设置主题的

customer-overview.component.ts
export class CustomerOverviewComponent implements OnInit{
 constructor(
 private appCommonService: AppCommonService)

 ngOnInit(){
  this.appCommonService.toolbarTitle.next('Customer-Overview');
  })
 }
}

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 2017-12-27
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2016-05-09
    • 2013-08-06
    • 2016-11-02
    相关资源
    最近更新 更多