角度将嵌套数组存储在component.ts中

时间:2018-06-28 12:11:28

标签: javascript arrays angular typescript components

当我尝试嵌套数组时,Angular为我的代码抛出错误。有人可以帮我吗?我的代码如下:

parents = {
    pfirst_name: '',
    pmiddle_name: '',
    plast_name: '',
    ...
}

students = {
    sfirst_name: '',
    smiddle_name: '',
    slast_name: '',
    ...
}

both = {
    this.parents,  
    this.students  
}

我收到此错误:

ERROR in ./src/app/app.component.ts
Module parse failed: Unexpected token (61:18)
You may need an appropriate loader to handle this file type.
|         };
|         this.both = {
|             this: .parents,
|             this: .students 
|         };

我还尝试了另一种方式:

both = {
    parents = {
        pfirst_name: '',
        pmiddle_name: '',
        plast_name: '',
        ...
    },
    students = {
        sfirst_name: '',
        smiddle_name: '',
        slast_name: '',
        ...
    }
}

我收到此错误:

ERROR in src/app/app.component.ts(18,9): error TS2552: Cannot find name 'parents'. Did you mean 'parent'?
src/app/app.component.ts(18,17): error TS1312: '=' can only be used in an object literal property inside a destructuring assignment.
src/app/app.component.ts(28,9): error TS2304: Cannot find name 'students'.

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的第一种方法是使用对象,而不是数组。试试这个:

// Array
both = [
    this.parents,  
    this.students  
];
// Or this alternatively
both = {
    parents: this.parents,  
    students: this.students  
};

在第二种方法中,您必须使用:而不是=,例如:

both = {
    parents: {
        pfirst_name: '',
        pmiddle_name: '',
        plast_name: '',
        ...
    },
    students: {
        sfirst_name: '',
        smiddle_name: '',
        slast_name: '',
        ...
    }
}