Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided:

"other_lessons": [
    {
        "id": 290,
        "name": "Christmas Test  #290",
        "course": {
            "id": 43,
            "name": "Christmas Test ",
            "description": "",
            "teacher": {
                "id": 4,
                "name": "Sandy's Teacher",
                "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0e0d0c2f1c410c0002">[email protected]</a>",
                "role": "TEACHER",
                "token": "abcd",
                "about": "Blah blah blah ",
                "phone": "2222222222",
                "image_url": "xyz",
                "payment_information": {}
            }
]

The objective is to access the details of course.name and course.id from the data. However, an error keeps surfacing in my developer console:

ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer] (ng:///AppModule/AppTileComponent.ngfactory.js:30)
at Object.debugUpdateRenderer [as updateRenderer] (vendor.bundle.js:105951)
at checkAndUpdateView (vendor.bundle.js:105102)
at callViewAction (vendor.bundle.js:105445)
at execComponentViewsAction (vendor.bundle.js:105377)
at checkAndUpdateView (vendor.bundle.js:105103)
at callViewAction (vendor.bundle.js:105445)
at execComponentViewsAction (vendor.bundle.js:105377)
at checkAndUpdateView (vendor.bundle.js:105103)
at callViewAction (vendor.bundle.js:105445)

Oddly enough, fetching id and name from the JSON data works just fine. The code snippet I've implemented looks like this—I'm passing the details to the selector tag as follows:

<widget-app-tile>

homepage.component.html

<widget-app-block title="You may be interested in">
<div class="row">
  <div class="col-md-6" *ngFor="let lesson of lessons">
    <widget-app-tile [lesson]="lesson"></widget-app-tile>
  </div>
</div>
</widget-app-block>

app-tile.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { Lesson } from '../../models/models';

@Component({
  selector: 'widget-app-tile',
  templateUrl: './app-tile.component.html',
  styleUrls: ['./app-tile.component.css']
})

export class AppTileComponent implements OnInit {

  @Input() lesson : Lesson = <Lesson> {}

  constructor() { }

  ngOnInit() {
  }

}

app-tile.component.html

<div class="content-details">
<div class="details">
  <h5>{{lesson.course.name}}</h5>
  <img class="icon" src="/assets/images/logo-transparent.png" alt="No Internet" align="right"/>
</div>

When attempting to fetch {{lesson.course.name}}, it triggers an error. Yet, calling {{lesson.name}} or {{lesson.id}} functions smoothly and displays the data.

I've utilized the Cerialize Library. Below is my model class structure:

model.ts

import { deserialize, deserializeAs, Deserialize } from 'cerialize';

/* UTILITY METHODS */

export function cast(data, modelClass) {
  return Deserialize(data, modelClass)
}

export function castCollection (collection, modelClass) {
  return collection.map( item => cast(item, modelClass))
}

/* MODELS */


export class Course {

  @deserialize id: number
  @deserialize name: string

}

export class Lesson {

  @deserialize id: number
  @deserialize name: string
  @deserializeAs(Course) course : Course
}

This model is employed for extracting data; interfaces are not used.

EDITS

Testing on the home page directly yielded positive results, whereas implementing app-tile.component.ts did not provide desired outcomes. The code snippet integrated is as follows:

homepage.component.html

<div class="" *ngFor="let lesson of lessons" >
#{{lesson.id}} - {{lesson.name}}; Course: {{lesson.course.name}}
</div>

<widget-app-block title="You may be interested in">
<div class="row">
  <div class="col-md-6" *ngFor="let lesson of lessons">
    <widget-app-tile [lesson]="lesson"></widget-app-tile>
  </div>
 </div>
</widget-app-block>

The above implementation works without errors. One additional detail is presented below:

homepage.component.ts

export class MyClassesComponent implements OnInit {

  lessons : Lesson[] = []

  constructor(private http : HttpClient) { }

  ngOnInit() {
  }

  ngAfterViewInit(){
    this.http.get("/ui/student/home").subscribe( data => {
      this.lessons = castCollection(data['other_lessons'], Lesson)
    })
  }

Answer №1

To format dates in Angular, you can utilize the Angular date pipe. Check out more formats here or create your own format string. Here's an example from the Angular site:

<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>

It's great that the issue was resolved. For future reference, I recommend using the |json pipe to check if you are receiving the proper object and data. Additionally, use the ? operator to avoid runtime errors due to null values. For example, in your code binding, use {{lesson?.course?.name}}

Try structuring your code like this:

export class AppTileComponent implements OnInit {
    private _lesson : Lesson;

     @Input()
     set lesson(less: Lesson) {
       this._lesson = (less) ||  new Lesson();
     }
     get lesson(): Lesson{ return this._lesson ; }  

  constructor() { }
  ngOnInit() {
  }
}

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

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Obtaining JSON data with PHP

I am struggling to retrieve JSON data using PHP from a specific URL. The URL contains JSON data in the format shown below: { "Profile":{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40212223002 ...

Having trouble getting JSON data to display in an Ionic HTML file

After successfully retrieving data from my API and logging it in the console, I am facing difficulties accessing it through my HTML file. Despite looking into other questions for a solution, I still couldn't figure out why it isn't working. Here ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

Utilizing JQuery to dynamically create distinct classes for elements within a for loop

I am working on looping through a JSON file and creating elements to insert specific information. The challenge I am facing is that I need each element to have a unique identifier defined by something like element class = 'name'[i], where i repre ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

Using Spring's jsonview to extract a parameter from a request

I am trying to pass a request parameter to a method that returns a property of JSON. How can I achieve something like this: { "project":{ "id": 1, "cashflow":[{ date: "2014-09-27T18:30:49-0300", value:-1000, ...

What is the best way to extract a specific value from a line of data using JavaScript (JSON)?

My current task involves extracting the "correctAnswers" from a specific number. Let's take a look at this JSON example: { "questions": [ { "number": 3, "question": "☀️ ➕ ...

A comprehensive guide on creating and searching for tables in Angular

Seeking guidance on creating a table in Angular to display data fetched from an API. Currently developing a library management project with a reservation feature for books. Working on the search page where users can search and view book information in a ta ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...

Issue encountered while attempting to run an Angular project using the CLI: "Module not found - Unable to resolve 'AngularProjectPath' in 'AngularProjectPath'"

Just like the title suggests, I'm facing an issue with compiling my angular project. It seems to be having trouble resolving my working directory: Error: Module not found: Error: Can't resolve 'D:\Proyectos\Yesoft\newschool& ...

How to access a specific key in a JSON string using square brackets in PHP

My current challenge involves dealing with an array: [{"title":" \ud83c\uddfa\ud83c\udde6 \u041b\u0443\u0447\u0448\u0435\u0435 \u043a\u0430\u0437\u0438\u043d\u04 ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

Do const generics similar to Rust exist in TypeScript?

Within TypeScript, literals are considered types. By implementing const-generics, I would have the ability to utilize the value of the literal within the type it belongs to. For example: class PreciseCurrency<const EXCHANGE_RATE: number> { amount ...

Validation of forms in Angular 2: Handling fields within components

Imagine a scenario where I have the following structure: <form> <my-component></my-component> </form> The "my-component" itself contains an "input" element in its template. How can I ensure that my "form" can recognize and int ...

Implementing Angular2 Service into component's base class

Looking to create a base class that can perform common tasks for components throughout their life-cycle. Need this base class to have access to a service as well. How can I inject it? While using a singleton instead of a service is an option, it may not al ...

Identify the specific directive selector utilized within the template by examining multiple directive selectors

My directive has two selectors, dirA and dirNotA, and I need to determine which one was used within the directive itself. I want to avoid creating multiple directives or using parameters in order to achieve this. Ideally, I would like to have a single dire ...