【问题标题】:Angular storing nested arrays in component.tsAngular 在 component.ts 中存储嵌套数组
【发布时间】:2018-12-07 12:27:53
【问题描述】:

当我尝试嵌套数组时,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'.

非常感谢任何帮助!

【问题讨论】:

  • 这是一个嵌套的对象。语法是{ outer: { inner: 1 } },注意对象字面量中没有等号。

标签: javascript arrays angular typescript components


【解决方案1】:

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

// 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: '',
        ...
    }
}

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 2017-12-31
    • 2015-10-26
    • 2020-11-19
    • 1970-01-01
    • 2012-04-04
    • 2018-07-06
    • 2023-02-10
    • 2019-02-25
    相关资源
    最近更新 更多