Angular 2 (or 4) object serialization

Recently came across the following conundrum:

Standards

Typescript documentation suggests creating object definitions with underscore-prefixed private members, allowing getters / setters to use the original name 'from the specified members, giving indirect public access (as they should).

Angular documentation recommends otherwise, however it does not provide an example of using getters and setters for a private variable in defining their example objects.

Problem

I followed the Typescript coding standard the most. Let's take the following class, for example:

public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}
}

      

Using the following code to serialize it to JSON:

console.log(JSON.stringify(new Foo()));

      

... will produce:

{
    '_bar': 'Baz'
}

      

Questions

  • With these "guidelines" and just guidelines in mind, what would be the Angular-level handling of object definitions that would allow direct serialization?
  • In my example, surely the private access modifier should not allow direct access to its value? What am I missing in my understanding of using the private access modifier here?

I have done most of the reading in other StackOverflow articles and posts regarding various ways to handle serialization, want to hold back the "how" and rather ask the "why" in relation to the behavior mentioned.

Any feedback would be greatly appreciated! :)

respectfully

+3


source to share


1 answer


You can customize serialization by doing toJSON()

public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}

    toJSON() {
      return {bar: _bar};
    }

    static fromJSON(json) {
      ...
    }
}

      

See also http://choly.ca/post/typescript-json/



Getters and setters are pure TypeScript and are completely unrelated to Angular.

private

intended only for static analysis in TypeScript. When it is passed to JS private

, it will no longer exist. It becomes a plain old JS object and JSON.stringify

treats it like this.

+3


source







All Articles