The receiver model and setter for the child model do not work in angular 2/4

I have a situation where I defined three model classes as shown below

export class Parent 
{
    name: string;
    containers: Container[];  
}

export class Container
{
    desc: string;
    sets: Sets[];  
}


export class Sets
{
    private _data?: any[];
    private _dataSet?: any[];

    get data() 
    {
        if (this.dataSet && this.dataSet.length > 0) 
        {
            return this._dataSet[0].data;
        }
        return this._data;
    }

    set data(data: any[]) 
    {
        this._data = data;
    }

    get dataSet() 
    {
        return this._dataSet;
    }

    set dataSet(dataSet: any[]) 
    {
        this._dataSet = dataSet;
    }
}

The problem is this: the method getterand setterclass Setwill not be called unless I do it explicitly new Set()(I don’t know if it really is new Set()).

For instance:

"name": "vik",
"containers": [
{
    "desc": "something",
    "sets": [
    {
        "dataSet": [
        {
            "data":[
            {
                // Object
            }]
        }]
    }]
}]

When i do:

let response:Parent = responseObj;
console.log(response.containers[0].sets[0].data)

it should return a DataSet value, but instead it returns undefined.

But if I do:

let response:Parent = responseObj;
console.log(new Sets(response.containers[0].sets[0]).data)

returns me the correct value.

Did I miss something or how to improve the code to make it work?

+4
source share
2 answers

The problem is that your object comes from HTTP. What does it mean:

Http - . , , , :

"{"foo":"boor"}"

- JSON.parse(data) , :

{foo: "bar"};

JSON.parse , . , . , .

, , , getter/setters e.t.c. aka dto. , dto, , dto .

new Sets(response.containers[0].sets[0])

, , , . , , - Mapper dto, . , "" "" .

, .

UPD:

let rawData = '{"name":"Vitalii"}';
let person1 = JSON.parse(rawData);

function Person(data) {
  this.name = data.name;
  this.say = function() {
    console.log(`Hi, ${this.name}`);
  }
}

let person2 = new Person(person1);
person2.say();

// person1 and person2 have the same data inside. But: 

console.log(person2 instanceof Person); // true
console.log(person1 instanceof Person); // false
Hide result

, , .

+1

, (- ) , , .

:

import { Type, plainToClass } from 'class-transformer';

export class Parent {
    @Type(() => Container)
    name: string;
    containers: Container[] = [];  
    static fromJson(json: any): Parent {
      return plainToClass<any, Parent>(Parent, json);
    }
}

export class Container{
    @Type(() => Set)
    desc: string;
    sets: Set[] = [];
}

export class Set{
    private _data?: any[];
    private _dataSet?: any[];

    //your code
}

let response:Parent = responseObj;
console.log(Parent.fromJson(response).containers[0].sets[0].data)

, ,

, ~

+1

Source: https://habr.com/ru/post/1689553/


All Articles