Angular 2 / Type脚本类到JSON对象

时间:2016-09-25 07:34:59

标签: json angular typescript

我正在尝试创建一个可用于将json对象发送到REST API的类。这是我需要发送的json对象。

{
  "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"
  }
}

我尝试创建这样的类并尝试通过创建对象this.library.WFAllowdTeam.WFAllowdTeam = 'team';来设置数据,请找到我在这里创建的类,

   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;
    }

错误是,

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)

任何帮助克服这个问题的人都会非常感激。

2 个答案:

答案 0 :(得分:4)

您需要首先实例化这些(类)成员。

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();
    }
}

答案 1 :(得分:1)

您需要先创建WFAllowdTeam的实例,然后才能修改其任何属性。

this.library.WFAllowdTeam = new WFAllowdTeam();
this.library.WFAllowdTeam.WFAllowdTeam = 'team';