无法从Angular2中的JSON Data子对象获取键值

时间:2017-12-11 13:07:18

标签: json angular typescript

我正在处理角度并尝试从子对象的键值填充数据。 JSON数据在这里:

"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": {}
            }
]

我想要做的是获取course.name和course.id数据的详细信息。而且我'在我的开发者控制台中始终收到此错误。

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)

但是对于JSON数据中的id和name工作正常。我实现的代码是这样的,我将细节传递给选择器标签,即

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

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

}

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

正如您所看到的那样,如果我拨打 {{lesson.course.name}} ,则会引发错误,但是当我称之为 {{lesson.name}} {{lesson.id}} 它工作正常并显示数据。

我使用了Cerialize Library,我的模型类是这样的:

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
}

所以这是我用来获取数据的模型,而不是使用接口。

EDITS

我已尝试在我的主页上获得结果并且结果很好,但在使用中但我不知道为什么 app-tile.component.ts 不是工作正常。我实施的ocde如下:

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>

这里工作正常。还有一个细节如下:

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

1 个答案:

答案 0 :(得分:1)

要在anugla中形成日期,你可以使用角度日期piple:https://angular.io/api/common/DatePipe这里给出更多格式或者你可以根据你自己传递格式字符串,角度网站的例子之一

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

它的好问题得到了解决,但是为了将来我建议你使用|json管道,它可以帮助你找到你是否得到了对象,你也得到了正确的数据

并且还使用?运算符来检查空值,这样您就不会在运行时获得ex的错误。你在绑定{{lesson?.course?.name}}

中的代码

制作这样的代码并尝试

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