0

I'm working on angular and try to populate the data from the child object's key value. The JSON data is here :

"other_lessons": [
    {
        "id": 290,
        "name": "Christmas Test  #290",
        "course": {
            "id": 43,
            "name": "Christmas Test ",
            "description": "",
            "teacher": {
                "id": 4,
                "name": "Sandy's Teacher",
                "email": "[email protected]",
                "role": "TEACHER",
                "token": "abcd",
                "about": "Blah blah blah ",
                "phone": "2222222222",
                "image_url": "xyz",
                "payment_information": {}
            }
]

What I'm trying to do is to get the details of the data of course.name and course.id. And I' getting this error all the time 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)

What but working fine for the id and name in the JSON data. The code I implemented is like this, I'm passing the details to the selector tag i.e.,

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

As you can see that if I call the {{lesson.course.name}} it throws up an error but when I call this {{lesson.name}} or {{lesson.id}} it works fine and shows up the data.

I have used the Cerialize Library and my model class is this :

model.ts

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

/* UTILTY 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
}

So this is the model which I'm using to get the data, not using interfaces.

EDITS

I have tried getting the results on my home page itself and the results are coming fine, but in using but I don't know why the app-tile.component.ts is not working fine. The ocde which I implemented 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>

And here it is working fine. And one more details are as follows :

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)
    })
  }
4
  • is that worked for you ?? Commented Dec 11, 2017 at 13:17
  • can you please remove <widget-app-block title="You may be interested in"> for now and try its working or not Commented Dec 11, 2017 at 14:15
  • can you pleas AppTileComponent class as i given in my answer Commented Dec 11, 2017 at 14:16
  • udpated answer with some tips you can use to find out problem next time Commented Dec 11, 2017 at 18:07

1 Answer 1

1

to formate date in anugla you can make use of angular date piple : https://angular.io/api/common/DatePipe here given more format or you can pass formate string according to your self , one of the example for angular site

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

Its good issue got resolved but for future I suggest you make use of |json pipe that can help you to find you are getting object or not and also you are getting proper data or not

and also make use of ? operator for checking null values so you will not get error at runtime for ex. in you code in binding {{lesson?.course?.name}}


make code like this and try

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() {
  }
}
Sign up to request clarification or add additional context in comments.

18 Comments

I've tried implementing your both the suggestions and it was not working out since lesson is an Array so I have tried doing this @Input() lesson : Lesson = Array<Lesson>(); and I was getting this error Type 'Lesson[]' is not assignable to type 'Lesson'. Property 'id' is missing in type 'Lesson[]'. and when I implemented for a class that is @Input() lesson: Lesson = new Lesson(); it gave me the same error cannot read property "name". And tried using the interceptor method and still no luck same error cannot read property "name"
@AlokKumarVerma - updated have try..as its array you need to access it by using index or make use of *ngFor of angular
Sorry, same error that is Type 'Lesson[]' is not assignable to type 'Lesson'. Property 'id' is missing in type 'Lesson[]'.. I have tried doing this @Input() lesson: Lesson = new Lesson() but now no heading is coming up.
My confusion is that how it is fetching the lesson.id and lesson.name and why not lesson.course.name or lesson.course.id?
@AlokKumarVerma - updated my answer have a look and update things according to it..check the class structure also
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.