angular - 如何在 Angular 中从服务中获取组件名称而不使用像视图容器引用这样的私有 API
问题描述
我需要服务内的组件名称,它在服务控制台.log(this.vcr ['_view'].component)中调用方法;console.log(this.vcr['_view'].component.constructor.name);
解决方案
在服务中,您需要设置用于从组件类名称中保存组件名称的属性。因此,您必须从服务中对属性名称的 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
从应用程序的任何位置设置和获取当前组件名称。希望这对你有用。
推荐阅读
- javascript - Promise.all 的问题
- sql - 根据sid查询sys.database_principals
- swift - 如何在一个函数中同时运行两个 enumerateNodes
- javascript - Xamarin WebView Audio.Play 不是函数
- pine-script - PineScript:如何只获得前一天的 OHLC 而不是前一天的 OHLC 系列?
- css - 如何在引导网格中将 *ngFor 生成的内容居中?
- onclick - MarkitUp Onclick 事件
- php - 尝试访问 int 类型值的数组偏移量 { DefaultValueBinder.php 第 82 行}
- node.js - Socket.io 如何离开房间
- c++ - 错误:对成员“show”的请求在 Qt 中不明确