0

I'm working through the Angular2 Tour of Heroes tutorial and I'm trying to learn how to work with services. I was able to get the basic tutorial to work but when I attempt to get a little more complex, my app breaks and I'm not sure what I'm doing wrong.

The basic model which works fine consists of an mock-heroes object along with a hero.ts file that specifies the type of each line.

Here is the Tour of Heroes Tutorial I am referring to: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

hero.ts file:

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

mock-hero.ts file:

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

If I want to add a nested object, such as accounts, I get the error:

Object literal may only specify known properties, and 'accounts' does not exist in type 'Hero'.

hero.ts file:

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
}

mock-hero.ts file:

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

So, I get that I need to identify "accounts" but I'm missing what I classify "accounts" as so I can nest objects properly.

Thanks in advance.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255

1 Answers1

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>;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255