【问题标题】:How can I display my json object with TypeScript in Angular?如何在 Angular 中使用 TypeScript 显示我的 json 对象?
【发布时间】:2019-07-03 16:58:27
【问题描述】:

我正在尝试使用 *ngFor 在 html 中显示我的 json 数组,但我认为它不起作用,因为它需要在 AppComponent 类中。但是,如果我尝试移动源代码以在 AppComponent 类中创建 json 对象,则会出现错误。

这是我的 app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  s = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  myHero = this.s[0];

}

interface Person {
  name: string;
  year: number; 
}

var people: Person[] = [{ name: 'robert', year: 1993 }];
var newPerson: Person = { name: 'joe', year: 1992 };

people.push(newPerson);

newPerson = {name: 'jose', year: 1997};

people.push(newPerson);


console.log(people[2].name);

这是我的 app.component.html 文件

<p>HEllo</p>


<ul>
  <li *ngFor="let name of s">
    {{ name }}
  </li>
</ul>


我想对我在 html 文件中所做的事情做一些事情,但使用另一个数组

【问题讨论】:

  • 您能否向我们展示如何您使用 html 上的其他数组来做到这一点?你遇到的error是什么。

标签: arrays json angular typescript


【解决方案1】:

您只需要将应用组件视为一个类。这不应该引发任何错误。

import { Component } from '@angular/core';
interface Person {
  name: string;
  year: number;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  public s = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  public myHero = this.s[0];
  public people : Person[];
  public newPerson: Person;

  constructor() {
    this.people = [{ name: 'robert', year: 1993 }];
    this.newPerson = { name: 'joe', year: 1992 };

    this.people.push(newPerson);

    this.newPerson = {name: 'jose', year: 1997};

    this.people.push(newPerson);


    console.log(this.people[2].name);
  }

}

【讨论】:

  • 构造函数不是初始化数据的最佳位置;使用 angular 提供的ngOnInit 生命周期钩子。
  • 是的,它可能应该被分解成有意义的函数。我的回答只是向他展示如何让它正常工作。
【解决方案2】:

您需要将语句放在您没有执行的类的方法/构造函数中,因此会出现编译时错误。 ngOnInit() 是您的组件初始化其数据的理想位置。

您的组件应如下所示:

export class AppComponent implements OnInit {
  people: Person[] = [];

  ngOnInit() {
    this.people  = [{ name: 'robert', year: 1993 }];
    let newPerson: Person = { name: 'joe', year: 1992 };
    this.people.push(newPerson);
    newPerson = {name: 'jose', year: 1997};
    this.people.push(newPerson);
    console.log(this.people[2].name);
  }
}

interface Person {
  name: string;
  year: number; 
}

还有模板

<ul>
  <li *ngFor="let p of people">
    {{ p.name }}, {{ p.year }}
  </li>
</ul>

这里有一个stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2019-10-29
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多