Exploring Angular2 Heroes Guide - Declaring Hero Properties with Nested Objects

Currently, I am diving into the Angular2 Tour of Heroes guide and striving to grasp the concept of services. So far, I've successfully implemented the basic tutorial, but as I attempt to add more complexity, my application crashes without clear reasons.

The initial model that functions properly comprises a mock-heroes object along with a hero.ts file defining the structure of each entity.

You can find the specific Tour of Heroes Tutorial I am following here: 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';

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

When attempting to introduce a nested object like 'accounts', I encounter the following error message:

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

hero.ts file (updated):

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

// HEROES array now includes an 'accounts' nested within the main object
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
            }
        ]
    }
]

I understand the need to define "accounts", but I'm uncertain about how to categorize it to correctly nest objects.

Thank you for any assistance provided.

Answer â„–1

interface UserAccount {
    accountNumber: string;
    accountHolderName: string;
    accountType: string;
    availableBalance: number;
}

class Superhero {
    superheroId: number;
    firstName: string;
    lastName: string;
    streetAddress: string;
    suiteNumber: string;
    city: string;
    state: string;
    zipCode: string;
    userAccounts: Array<UserAccount>;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Jaydata is a powerful open source library for interacting with databases

I rely on jaysvcutil for compiling OData $metadata and generating JayDataContext.js, which is truly impressive. However, I prefer to work with Typescript without using import/export syntax or other third-party tools like requirejs or systemjs. Even thoug ...

How to pass a JSON object to a component's constructor in Angular 2

In a unique situation, my primary component config.editor.component performs extensive processing and generates various JSON objects. I am content with this approach. The template for this component then proceeds to render another component - api.entry.com ...

Initial binding of Angular2 ControlGroup valueChanges event

My form contains <input type="text"> elements and I've noticed that ControlGroup.valueChanges is triggered during initial data binding when using [ngFormModel] and ngControl. As a result, it gives the impression to the user that the form has al ...

Jasmine's await function often leads to variables remaining undefined

When testing a function, I encountered an issue where a variable is created and assigned a value, but the payload constant always remains undefined. campaigns-card.component.ts async ngOnInit() { const { uid } = await this.auth.currentUser const { ...

"Encountering a module not found issue while trying to

Attempting to test out 3 node modules locally by updating their source locations in the package.json files. The modules in question are sdk, ng-widget-lib, and frontend. ng-widget-lib relies on sdk, while frontend depends on ng-widget-lib. To locally build ...

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. The values that are displaying correctly are the ones selected from the dropdown menu. However, the numbers I manuall ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Dealing with Errors in Angular 2/4 using forkJoin for Multiple URLs

I am currently using Angular 2 and implementing forkJoin for a particular scenario where I need to make multiple REST calls in parallel. Below is the function I am using: private getBatchObservableData(data: Array<Widget>): Observable<any> { ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

For editing values that have been dynamically inserted

In my JSON data, there is a variable named address that contains multiple objects (i.e., multiple addresses). I am displaying these multiple addresses as shown in the following image: When clicking on a specific address (e.g., addressType: Business), t ...

"Troubleshooting: Unspecified getInitialProps in Nextjs when passing it to a layout component

Greetings, I am a newcomer to Next.js and facing an issue with passing dynamic properties to the header component. Despite using getInitialProps in Next.js successfully, I encounter the problem of receiving 'UNDEFINED' when these properties are p ...

The conditional expression is failing to function properly when applied to multiple form controls in the latest version of @rxweb/[email protected]

I am currently working on a form that includes various field validations based on a boolean variable called isNewCustomer. this.customerDetailsFormGroup = this._formBuilder.group({ customer: [this.order.customer_details.name, [RxwebValidators.r ...

Utilizing JavaScript libraries in a TypeScript project: A step-by-step guide

Currently, I am working on an existing TypeScript AngularJS project and looking to incorporate d3js. However, due to restrictions with the corporate proxy, I am unable to use tools for downloading or managing dependencies. As a result, I have opted for man ...

Combining vue with deno and vscode: A guide to seamless development integration

How can I set up Visual Studio Code for a Vue project using Deno? Important note - the issues mentioned here only pertain to highlighting in VSCode, as the builds, development, and scripts are functioning correctly! Deno + Vue is an appealing choice! You ...

The CORS policy has blocked access to XMLHttpRequest at 'https://saja.smjd.ir/api/Account/login' from the specified origin 'http://**'

I have successfully completed my project using Angular 9 on the frontend and asp.net core 3 on the backend, and deployed it to a server. However, I am facing an issue when trying to obtain or use a token from the server. Access to XMLHttpRequest at 'h ...

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...

Step-by-step guide for adding an object to a Material UI select component

I am in the process of incorporating a Select component with reactjs material ui and typescript. Yet, I encounter this typing error: Property 'id' does not exist on type 'string'. Property 'name' does not exist on type ' ...

Alter the class based on the incoming string from the rxjs stream

I have a stream that outputs strings, and based on these strings I want to apply certain classes to a specific tag: If the string is "ok", add class "fa-check" If the string is "loading", add classes "fa-spin" and "fa-spinner" If the string is "error", a ...

Unable to perform the upgrade to Angular 6 due to an invalid range

I'm in the process of upgrading to Angular 6 As I follow the upgrade guide, I run into this issue: > ng update @angular/core Invalid range: ">=2.1.0" That's all the information I have. There are no additional warnings or ...