如何在Angular中使用TypeScript显示我的json对象?

时间:2019-07-03 16:58:27

标签: arrays json angular typescript

我试图使用* 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文件中的内容做一些处理,但是要对另一个数组做

2 个答案:

答案 0 :(得分:2)

您只需要像对待类一样对待应用程序组件。这应该不会引发任何错误。

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

}

答案 1 :(得分:1)

您需要将语句放置在您未执行的类的方法/构造函数中,因此会产生编译时错误。 git push是组件初始化其数据的理想位置。

您的组件应如下所示:

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

这里是stackblitz