Home > Mobile >  Manually set value object's properties in typescript
Manually set value object's properties in typescript

Time:10-26

I am trying to manually set a value object's properties if the data for it does not exist from the service call.

The data comes from a service call (it works, because I get data back). The object looks from the service call looks like this:

export class AllHouseData {
    dataList: HouseResponse[];
    numberOfHouses: number;
}

The value object for the HouseResponse object looks like this:

export class HouseResponse {
    id: number;
    name: string;
    settings: HouseSettings[];
}

The value object for the HouseSettings object looks like this:

export class HouseSettings {
    id: number;
    houseCode: string
    parking: any;
}

Here is the code where I am trying to assign the object's properties:

export class HouseComponent implements OnInit {
    houseData: AllHouseData;

    callHouseService(houseList) {
        this.houseService.getHouseData(houseList).subscribe((data) => {
            this.houseData = data;
            if (data === null) {
                this.houseData.dataList = [
                    {
                        id: 0,
                        name: "",
                        settings: [{ id: number, houseCode: "", parking: false }],
                    },
                ];
            }
        });
    }
}


Typescript gives me no errors when trying to set the data manually. However, in the console of the browser, I get the following error: ERROR TypeError: Cannot set properties of null (setting 'dataList').

My question is, what is the correct way to go about setting this object manually?

CodePudding user response:

Looks like your getHouseData call is returning null and you have no check for this.

If you need this.houseData to always have a value I would recommend a constructor with default values.

export class HouseSettings {
  constructor(public id = 0, houseCode = '', parking = false) {}
}
export class HouseResponse {
  constructor(public id = 0, name = '', public settings = [new HouseSettings()]) {}
}

export class AllHouseData {
  constructor(public dataList = [new HouseResponse()], public numberOfHouses = 0) {}
}

then in your subscription you could simply use:

data => this.houseData = data ?? new AllHouseData()
  • Related