【问题标题】:Cannot get the key value from JSON Data child object in Angular2无法从 Angular2 中的 JSON 数据子对象获取键值
【发布时间】:2017-12-12 02:28:59
【问题描述】:

我正在研究角度并尝试从子对象的键值中填充数据。 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>

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>

如您所见,如果我调用 {{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
}

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

编辑

我已经尝试在我的主页本身上获取结果并且结果很好,但是在使用中但我不知道为什么 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)
    })
  }

【问题讨论】:

  • 这对你有用吗??
  • 你能不能请你删除 现在试试它的工作与否
  • 你能像我在回答中给出的那样请求 AppTileComponent 类吗
  • 更新了答案,提供了一些提示,您可以在下次发现问题时使用

标签: json angular typescript


【解决方案1】:

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

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

它的好问题得到了解决,但对于未来我建议您使用|json 管道,它可以帮助您发现您是否正在获取对象以及您是否正在获取正确的数据

并且还使用? 运算符来检查空值,这样您就不会在运行时遇到错误。在你的代码中绑定{{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() {
  }
}

【讨论】:

  • 我已经尝试实施你的两个建议,但由于课程是一个数组,所以我尝试这样做@Input() lesson : Lesson = Array&lt;Lesson&gt;();,我收到了这个错误Type 'Lesson[]' is not assignable to type 'Lesson'. Property 'id' is missing in type 'Lesson[]'.,当我实施时对于@Input() lesson: Lesson = new Lesson(); 的类,它给了我同样的错误,无法读取属性“名称”。并尝试使用拦截器方法,但仍然没有运气同样的错误无法读取属性“名称”
  • @AlokKumarVerma - 更新了 try..作为它的数组,您需要使用索引或使用 angular 的 *ngFor 来访问它
  • 抱歉,与 类型“Lesson[]”相同的错误不可分配给类型“Lesson”。类型“Lesson[]”中缺少属性“id”。。我试过这样做@Input() lesson: Lesson = new Lesson(),但现在没有标题出现。
  • 我的困惑是它是如何获取课程 ID 和课程名称的,为什么不获取课程名称或课程 ID?
  • @AlokKumarVerma - 更新了我的答案,看看并根据它更新内容..还要检查类结构
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 2017-06-03
  • 2015-08-14
  • 1970-01-01
  • 2018-06-02
  • 2015-04-03
相关资源
最近更新 更多