Cannot get the key value from JSON Data child object in Angular2

问题内容:

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": "abc@s.com",
                "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)
    })
  }

问题评论:

    
is that worked for you ??
    
can you please remove <widget-app-block title=”You may be interested in”> for now and try its working or not
    
can you pleas AppTileComponent class as i given in my answer

答案:

答案1:

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() {
  }
}

答案评论:

    
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”
– Alok Kumar Verma
2 hours ago
    
@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.
– Alok Kumar Verma
2 hours ago
    
My confusion is that how it is fetching the lesson.id and lesson.name and why not lesson.course.name or lesson.course.id?
– Alok Kumar Verma
2 hours ago
    
@AlokKumarVerma – let me see update my answer

原文地址:

https://stackoverflow.com/questions/47753683/cannot-get-the-key-value-from-json-data-child-object-in-angular2

添加评论

友情链接:蝴蝶教程