Angular:是什么让这个getter(s)与公共成员不同?
我正在开发一个angular应用程序,其中有一个包含几个不同模块的图表。每个模块都有一个模块类型,它是Angular:是什么让这个getter(s)与公共成员不同?,angular,Angular,我正在开发一个angular应用程序,其中有一个包含几个不同模块的图表。每个模块都有一个模块类型,它是ModuleType类型的枚举。单击模块时,我希望通过反向映射显示其模块类型 事件处理程序如下所示: handleModuleFocusChanged(args: ModuleSettingsEventArgs) { if (args.visible) { this.currentModuleType = args.module.type; } else { this.c
ModuleType
类型的枚举。单击模块时,我希望通过反向映射显示其模块类型
事件处理程序如下所示:
handleModuleFocusChanged(args: ModuleSettingsEventArgs) {
if (args.visible) {
this.currentModuleType = args.module.type;
} else {
this.currentModuleType = ModuleType.Undefined;
}
console.log('currentmoduletype = ' + this.currentModuleType + ' (' + ModuleType[this.currentModuleType] + ')');
}
现在我尝试了模块
的不同实现,这些实现在我看来是相同的(当然除了数据封装),但只有一个有效。为了测试它,我只将模块的实现更改为下面三个模块中的一个,重新编译并重新加载页面。因此,在所有三个测试中,其他一切都是相同的
1。公共成员:
导致正确的输出:currentmoduletype=1(创建)
2。与getter和private成员一起:
导致错误输出:currentmoduletype=undefined(undefined)
3。前者的速记版本:
导致错误输出:currentmoduletype=undefined(undefined)
我完全搞不懂为什么这三种方法只有一种有效。我错过了什么
这听起来像是重复的,但我做了一些研究,没有发现任何东西可以解释这种行为。模块对象没有用new
初始化,因此没有定义方法。您可以访问字段,因为它们(不确定这是否是正确的单词)是动态铸造的。换句话说,由于我不太了解您的示例,也不知道是谁在调用handleModuleFocusChanged(args:ModuleSettingsEventArgs)
让我们假设我们有一个http方法,如:
public getModules(): Observable<Module> {
return this.http.get<Module>(SOME_URL);
}
实际上,我使用new创建实例。但是基本的想法是好的,我会在这方面做更多的研究。也许第三方框架正在干扰我的对象。
export abstract class Module {
private fType: ModuleType;
constructor(type: ModuleType) {
this.fType = type;
}
public get type(): ModuleType {
return this.fType;
}
}
export abstract class Module {
constructor(private fType: ModuleType) {
}
public get type(): ModuleType {
return this.fType;
}
}
public getModules(): Observable<Module> {
return this.http.get<Module>(SOME_URL);
}
public getModules(): Observable<Module> {
return this.http.get<Module>(SOME_URL)
.map(module => new Module(module));
}
export abstract class Module {
constructor(module) {
this.type = module ? module.type : null;
}
// any method you wish
}