d7k d7k - 2 months ago 22
TypeScript Question

Angular 2/ Type Script classes to JSON object

I am trying to create a class that can use to send a json object to a REST API. This is the json object that i need to send.

{
"libraryName": "temp",
"triggerName": "trigger",
"currentVersion": "1.3",
"createdUser": "xyz",
"visibilityType": "private",
"WFAllowdTeam": {
"allowedTeam": "team1"
},
"WFLibraryHistory": {
"createdDate": "2016-7-7T05:10:04.106Z",
"modifiedDate": "2016-7-9T05:10:04.106Z"
}
}


I tried creating a class like this and tried to set the data by creating an object
this.library.WFAllowdTeam.WFAllowdTeam = 'team';
, Please find the class i created here,

class WFLibraryHistory {
public createdDate: any;
public modifiedDate: any;
}

class WFAllowdTeam {
public WFAllowdTeam: string;
}

export class Library {
public libraryName: string;
public triggerName: string;
public currentVersion: string;
public createdUser: string;
public visibilityType: string;
public libraryID: string;
WFLibraryHistory: WFLibraryHistory;
WFAllowdTeam: WFAllowdTeam;
}


The error is,

platform-browser.umd.js:937 TypeError: Cannot set property 'WFAllowdTeam' of undefined
at WFLibraryComponentAddNewWorkflow.createWorkflow (wf-library.component.new.workflow.ts:47)
at DebugAppView._View_WFLibraryComponentAddNewWorkflow0._handle_click_61_0 (WFLibraryComponentAddNewWorkflow.ngfactory.js:488)
at eval (core.umd.js:12718)
at SafeSubscriber.schedulerFn [as _next] (core.umd.js:9181)
at SafeSubscriber.__tryOrUnsub (Subscriber.ts:240)
at SafeSubscriber.next (Subscriber.ts:192)
at Subscriber._next (Subscriber.ts:133)
at Subscriber.next (Subscriber.ts:93)
at EventEmitter.Subject._finalNext (Subject.ts:154)
at EventEmitter.Subject._next (Subject.ts:144)


Any help to overcome this issue will be really appreciated.

Answer

You need to instantiate those (class) members first.

export class Library {
    public libraryName: string;
    public triggerName: string;
    public currentVersion: string;
    public createdUser: string;
    public visibilityType: string;
    public libraryID: string;
    WFLibraryHistory: WFLibraryHistory;
    WFAllowdTeam: WFAllowdTeam;

    constructor() {
       this.WFLibraryHistory = new WFLibraryHistory();
       this.WFAllowdTeam = new WFAllowdTeam();
    }
}