0

我正在学习 Angular2 Tour of Heroes 教程,并且正在尝试学习如何使用服务。我能够让基本教程开始工作,但是当我尝试变得更复杂一点时,我的应用程序崩溃了,我不确定我做错了什么。

可以正常工作的基本模型由一个模拟英雄对象和一个指定每行类型的 hero.ts 文件组成。

这是我指的英雄之旅教程: https ://angular.io/docs/ts/latest/tutorial/toh-pt4.html

hero.ts 文件:

export class Hero {
    id: number;
    firstName: string;
    lastName: string;
    street: string;
    suite: string;
    city: string;
    state: string;
    zipcode: string;
}

模拟英雄.ts 文件:

import { Hero } from './hero';

export const HEROES: Hero[] = 
[
    {
        "id": 101, 
        "firstName": "John",
        "lastName": "Doe",
        "street": "111 Main Street",
        "suite": "Apt. 111",
        "city": "Anytown",
        "state": "US",
        "zipcode": "55555-0000"
    }
]

如果我想添加嵌套对象,例如帐户,我会收到错误消息:

对象字面量只能指定已知属性,而“Hero”类型中不存在“帐户”。

hero.ts 文件:

export class Hero {
    id: number;
    firstName: string;
    lastName: string;
    street: string;
    suite: string;
    city: string;
    state: string;
    zipcode: string;
    accounts: ????;
    accountNum: string;
    accountName: string;
    type: string;
    availBalance: number
}

模拟英雄.ts 文件:

import { Hero } from './hero';

export const HEROES: Hero[] = 
[
    {
        "id": 101, 
        "firstName": "John",
        "lastName": "Doe",
        "street": "111 Main Street",
        "suite": "Apt. 111",
        "city": "Anytown",
        "state": "US",
        "zipcode": "55555-0000",
        "accounts": [ 
            {
                accountNum: "012345678",
                accountName: "Personal Checking",
                type: "checking",
                availBalance: 1000.00
            }
        ]
    }
]

所以,我知道我需要识别“帐户”,但我错过了我对“帐户”进行分类的内容,以便可以正确嵌套对象。

提前致谢。

4

1 回答 1

1
export interface Account {
    accountNum: string;
    accountName: string;
    type: string;
    availBalance: number;
}

export class Hero {
    id: number;
    firstName: string;
    lastName: string;
    street: string;
    suite: string;
    city: string;
    state: string;
    zipcode: string;
    accounts: Array<Account>;
}
于 2016-12-10T10:37:00.023 回答