[Resolved] Getter and Setter not accessible


I recently created a new project under Ionic 3. I usually use model with getter and setter, but recently it is impossible to access the methods of the models.

Example :

export class Element {
  private id:number;

  public getId():number{return this.id;}
  public setId(id:number){this.id=id;}
import { Element } from '../../models/element';


  private elements:Element[]=new Array<Element>();


this.elements.sort(function(a, b){
    if(a.getId() < b.getId()) return -1;
    if(a.getId() > b.getId()) return 1;
    return 0;

Error :

ERROR TypeError: a.getId is not a function
at http://localhost:8100/build/12.js:89:23
at Array.sort (native)
at Array.sort (http://localhost:8100/build/polyfills.js:1:9424)
at EditModelPage.webpackJsonp.294.EditModelPage.ionViewDidEnter (http://localhost:8100/build/12.js:88:25)
at ViewController._lifecycle (http://localhost:8100/build/vendor.js:17322:33)
at ViewController._didEnter (http://localhost:8100/build/vendor.js:17222:14)
at NavControllerBase._didEnter (http://localhost:8100/build/vendor.js:43482:18)
at NavControllerBase._transitionFinish (http://localhost:8100/build/vendor.js:43276:22)
at http://localhost:8100/build/vendor.js:43257:26
at t.invoke (http://localhost:8100/build/polyfills.js:3:9283)


...function (a: Element, b: Element)...

Not working, same error. Thanks

Resolved, it was necessary to fill the constructor with the properties :

  private id:number;

  public constructor(id:number){


  get Id():number{return this.id;}
  set Id(id:number){this.id=id;}
element = new Element(1);
console.log(element.Id); // 1

Thanks for your help !

Your code scheme isn’t appropriate for Angular, nor for JavascriptES6. There is no support for private properties in Javascript, so getters and setters of the sort you define just encourage confusion and weird bugs. And the whole philosophy of Angular’s Dependency Injection is to remove the need for intelligent data structures.

Porting Java into this framework is a common mistake. But I strongly suggest you use a code scheme that fits this framework. Example: use interfaces, not classes, to define objects. Or use classes as recommended in the official Angular style guide.

1 Like

I totally agree with everything in the previous post, and would also add that another downside is the amount of useless boilerplate code that these sorts of OOP-inspired “smart PODs” require, both within the class itself and in other places that use it. This distracts readers from seeing the important logic of the app.