Lukas-T
Lukas-T

Reputation: 11350

Angular: What makes this getter(s) different from a public member?

I'm developing an angular application where I have a diagram with several different modules. Each module has a module-type which is an enum of type ModuleType. When I click a module I want to display it's module-type via reverse-mapping as seen here.

The event handler looks like this:

handleModuleFocusChanged(args: ModuleSettingsEventArgs) {
  if (args.visible) {
    this.currentModuleType = args.module.type;
  } else {
    this.currentModuleType = ModuleType.Undefined;
  }

  console.log('currentmoduletype = ' + this.currentModuleType + ' (' + ModuleType[this.currentModuleType] + ')');
}

Now I tried different implementations for Module, which are equal in my eyes (except for data encapsulation of course), but only one of them works. To test it I only changed the implementation of Module to one of the three below, recompiled and reloaded the page. So everything else is the same in all three tests.

1. With public member: leads to correct output: currentmoduletype = 1 (Create)

export abstract class Module {
  constructor(type: ModuleType) {
      this.type = type;
  }

  public type: ModuleType;
}

2. With getter and private member: leads to wrong output: currentmoduletype = undefined (undefined)

export abstract class Module {
  private fType: ModuleType;

  constructor(type: ModuleType) {
      this.fType = type;
  }

  public get type(): ModuleType {
      return this.fType;
  }
}

3. Shorthand version of the former: leads to wrong output: currentmoduletype = undefined (undefined)

export abstract class Module {
  constructor(private fType: ModuleType) {
  }

  public get type(): ModuleType {
      return this.fType;
  }
}

I'm totally confused why only one of the three works. What do I miss here?


This sounds like it could be duplicate, but I did some research and found nothing that would explain this behaviour.

Upvotes: 0

Views: 51

Answers (1)

pezetem
pezetem

Reputation: 2541

the Module object is not initialized with new, thus the methods are not defined. You can access fields, because they are (not sure if that is proper word) dynamically casted. In other words, as I do not know much about your example and who is calling the handleModuleFocusChanged(args: ModuleSettingsEventArgs) lets assume we have a http method like:

public getModules(): Observable<Module> {
    return this.http.get<Module>(SOME_URL);
  }

this will lead to your case, object ModuleType is not created, just dynamically casted, but when you call it like:

public getModules(): Observable<Module> {
    return this.http.get<Module>(SOME_URL)
         .map(module => new Module(module));
  }

and the Module should like like:

export abstract class Module {
  constructor(module) {
      this.type = module ? module.type : null;
  }

  // any method you wish
}

Upvotes: 1

Related Questions