如何遍历打字稿中定义的json

时间:2020-02-19 05:42:42

标签: json angular typescript

我正在使用Angular。还有一个类似的问题,但没有得到回答-

How to loop through a JSON object with typescript

我没有收到任何错误或警告。但是我也没有得到输出。我正在尝试模仿twitter-api。我已经在打字稿中创建了json object,并且试图在HTML中遍历我的json。这是我的代码:

twitter-timeline.component.ts

  output: JSON;
  twitter_data:any = {
      statuses: [
        {screen_name:"tanzeel", status: "wonderful day, enjoying at beach"},
        {screen_name:"pablo", status: "what a lovely morning #surfing #beach #relax"},
        {screen_name:"ricky", status: "feeling sick :-( #typhoid"}
      ]
  }

  ngOnInit() {
    this.output = <JSON>this.twitter_data;
  }

twitter-timeline.component.html

<div class="container" *ngFor="let tweets of output; let i=index">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 text-column">
            <p class="screen-name">{{tweets.statuses[i].screen_name}}</p>
            <p class="user-status">{{tweets.statuses[i].status}}</p>
            <br>
        </div>
    </div>
</div>

我创建JSON对象的方式是否存在问题,或者我读取HTML值的方式是否存在问题。请纠正我。

我也尝试过这种JSON结构:

output: JSON;
obj: any = 
{
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"}, 
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"} 
};

1 个答案:

答案 0 :(得分:2)

您需要将*ngFor更改为*ngFor="let tweets of output.statuses; let i=index"

output是一个对象,因此,您不能像这样迭代对象,而要迭代数组output.statuses,然后可以获得类似的数据,

        <p class="screen-name">{{tweets.screen_name}}</p>
        <p class="user-status">{{tweets.status}}</p>

您需要将let tweets of output 更改为 let tweets of output.statuses

twitter-timeline.component.html

<div class="container" *ngFor="let tweets of output.statuses; let i=index">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 text-column">
            <p class="screen-name">{{tweets.screen_name}}</p>
            <p class="user-status">{{tweets.status}}</p>
            <br>
        </div>
    </div>
</div>

Working Stackblitz