首页 > 解决方案 > 如何在 Angular 中从服务中获取组件名称而不使用像视图容器引用这样的私有 API

问题描述

我需要服务内的组件名称,它在服务控制台.log(this.vcr ['_view'].component)中调用方法;console.log(this.vcr['_view'].component.constructor.name);

标签: angular

解决方案


Demo stackBlitz Link

在服务中,您需要设置用于从组件类名称中保存组件名称的属性。因此,您必须从服务中对属性名称的 setter 进行分类,并在模板文件中从服务中调用属性名称的 getter。

另一件事,通过使用,constructor.name您将无法在生产中获得正确的组件类名称实例。因为,在构建时代码运行缩小并且大类名称转换为小名称。因此,您将不会在代码的生产版本中获得全类名称。有关更多参考,请转到我的此链接... Dev.to

服务.ts

@Injectable()
export class ComponentNameService {
  _currentComponnetName: string = 'default';
  get currentComponnetName(){
     return this._currentComponnetName;
  }
  set currentComponnetName(name:string){
     this._currentComponnetName = name;
  }
}

app.component.ts

export class AppComponent  {
  setCurrentCmpName = "App-Component";
  constructor(private componentService: ComponentNameService){}
  ngOnInit(){
    this.componentService.currentComponnetName = this.setCurrentCmpName;
  }
}

app.component.html

<div class="name">
   current Component Name is : 
  <h5> {{componentService.currentComponnetName}} </h5>
</div>

在每个组件中,ngOnInit()您必须currentComponentName从应用程序的任何位置设置和获取当前组件名称。希望这对你有用。


推荐阅读