ionic4在模板中显示对象类型数据

ionic4 display Object type data in template

我在使用 Ionic 4 的 angular 模板中显示数据时遇到问题。

部分代码如下:

这里我向模板页面发送数据

item: any;
    
  constructor(public route: ActivatedRoute, items: Items) {
    this.route.queryParams.subscribe(item => {
      this.item = item;
    });
  }

这里是我在读数据

<div class="item-detail" padding>
    <h2>{{item.name}}</h2>
    <p>{{item.about}}</p>
  </div>

这里是控制台返回的数据对象值

{
name: "Burt Bear", profilePic: "assets/img/speakers/bear.jpg", about: "Burt is a Bear."}

所以问题是,如何使用 angular 在 HTML 模板上显示这些值?这给我一个错误:

FindingItemDetailPage.html:8 ERROR TypeError: Cannot read property 'name' of undefined

初始化物品道具,不要让它成为any。例如

public item = {}; // or a given class/model it's up to you.

在构造函数中不能保证项目存在,因此请确保这种情况并应用适当的行为。 (还是由你决定)

例如

constructor(public route: ActivatedRoute, items: Items) {
    this.route.queryParams.subscribe(item => {
      this.item = item || {} // class/model would be better;
    });
  }

最后进入模板,您可以设置 *ngIf

例如

<div class="item-detail" padding *ngIf="item.name">

要确保有一个项目,item.name 是一个例子,您可以使用 属性 来保证有一个项目。