Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 instantiate class with empty values

How do you instantiate the members as class with empty values?

Plunkr

I instantiate with

public members = new MemberClass();

but the console shows Members: {} so I'm unable to set the default empty values

so basically I'm trying to replicate an empty structure like:

this.members = [ 
    { 
      "Name" : "", "Id" : "", "Team" : "",
      "Cases" : {
        "history" : []
      }
    }
];
like image 556
Daniel S Avatar asked Jan 04 '23 01:01

Daniel S


1 Answers

Use interfaces ;) And this is a way you can create an Array with an empty object of type Member with properties set. I don't know the use case, at least I do not set the properties for empty objects/arrays of models, but here we go :)

So first your interfaces, which are:

export interface Member {
    Id: string;
    Name: string;
    Cases: Case[];
}
export interface History {
    Id: string;
    CaseNumber: string;
}
export interface Case {
    History: History[];
}

Then you create 3 functions to set the properties:

export function createMember(Id?:string,Name?:string, Cases?:Case[]): Member {
  return {
    Id,
    Name,
    Cases[createCase()]       
  }
}

export function createCase(History?:History[]): Case {
  return {
    History[createHistory()]
  }
}

export function createHistory(Id?: string,CaseNumber?:string): History {
  return {
    Id,
    CaseNumber
  }
}

And now in your component you can call the function createMember, that then calls the two other functions:

members = [createMember()];

PS, according to your models, the following is not the model of Member-array, they name and build doesn't match, but I have created the above, based on the models you have provided.

like image 133
AT82 Avatar answered Jan 15 '23 11:01

AT82