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

A universal TypeScript type for functions that return other functions, where the ReturnType is based on the returned function's ReturnType

Greetings to all TypeScript-3-Gurus out there! I am in need of assistance in defining a generic type GuruMagic<T> that functions as follows: T represents a function that returns another function, such as this example: fetchUser(id: Id) => (disp ...

Inserting an array into a MySQL database using PHP

I'm currently facing an issue when it comes to inserting values from this array. Here is an example: $arr = json_decode($_POST['dynfields'], true); //{"dynfields":{"dynfields[0][DescRepair]":"Desc repair","dynfields[0][NestParts]":"Part ...

Using Kotlin on the Android platform, learn how to convert a string into a JSON string

Seeking to convert a string into a JSON string using Gson. My desired outcome is to transform "email" into "{"email" : "$email"}" I have the function: fun serializeUserEmail(email: String): String { return &quo ...

"Comparing the use of single Angular libraries versus multiple libraries on npm

I am considering consolidating all my libraries (57 in total) into a single folder called @my-organisation/team. This is because each library has many dependencies on one another and managing versioning & dependencies separately would be difficult. After s ...

Efficient Ways to Utilize Global CSS in an Angular Project Without CLI

I am utilizing ASP.NET MVC as the server and Angular as the client application. Instead of a static index.html file, I have index.cshtml. The styles I am using are global styles rather than component-scoped. My query revolves around working with a bunch ...

What is the reason for TS expressing dissatisfaction about the use of a type instead of a type entry being provided

Below is a snippet of code for a Vue3 component that takes in an Array of Objects as a prop: <script lang="ts"> interface CorveesI { What: string, Who: string, Debit: number } export default { name: 'Corvees', props: { ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Break up JSON into distinct JSON files based on node value using Python

Looking to utilize Python to split a JSON file into separate files based on the "transactionTypeName" found within the transactions.details. Each file should include all details starting from careperson to username. Here is an example of the JSON file afte ...

Error Message: The Reference.update operation in Angular Firebase failed due to the presence of undefined value in the 'users.UID.email' property

Having recently started to use the Firebase database, I encountered an issue while trying to update the UID to the Realtime Database during signup. The error message displayed was: Error: Reference.update failed: First argument contains undefined in prop ...

Guide to making a fully interactive JSONObject

I am facing a small challenge. I have written a code that involves creating objects from JSONObject and adding data to them in a specific structure, as shown below: JSONObject outerObject = new JSONObject(); JSONArray outerArray = new JSONArray(); JSONOb ...

My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCoun ...

Obtaining data using Classic ASP from an ajax JSON post can be achieved by following these

I am currently working on sending data to classic asp using ajax json. The json successfully calls the asp page, but there is an issue with the data not reaching the backend. As a result, the database is unable to be modified based on the new sort order. ...

When using the TypeScript && operator, the resulting type is not determined by the second operand

Several past discussions on SO have touched upon the concept that the inferred type from && is based on the last expression. TypeScript’s failure to detect union type with an && operator Uncovering the reason behind the && opera ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

In Python, extract data from the top level of a JSON file

Looking for assistance with parsing a JSON stored as a string: message = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636 ...

JSONP is unable to utilize data fetched from an external API

I attempted to run an ajax request in order to retrieve a collection of items and display them through logging: https://i.stack.imgur.com/IK1qy.jpg However, when checking the console, the items appear as undefined: https://i.stack.imgur.com/3WOCa.jpg O ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...