【问题标题】:fetching post from api angularjs从 api angularjs 获取帖子
【发布时间】:2018-09-14 12:02:53
【问题描述】:

我有一个 JSON,我正在尝试获取表单对象。

{
  "userId": 123,
  "formId": "VC01",
  "form": [
    {
      "id": "F01",
      "caption": "Sighting",
      "type": "date"
    },
    {
      "id": "F02",
      "caption": "Ship Name",
      "type": "text"
    },
    {
      "id": "F03",
      "caption": "Aliens Count",
      "type": "number"
    },
    {
      "id": "F04",
      "caption": "Friendliness",
      "type": "number"
    },
    {
      "id": "F05",
      "caption": "Smartness",
      "type": "number"
    },
    {
      "id": "F06",
      "caption": "Description",
      "type": "text"
    }
  ],
  "lastChangedDate": "2017-10-30T17:23:43+00:00",
  "lastChangedBy": "Paddy"
}

我有 data.service.ts 用于获取 HTTP

getPosts() {
  return this.http.get('http://www.mocky.io/v2/59f7760a2f0000ab1d55864e')
    .pipe(map(res => res.json()));
}

在控制器中user.component.ts

export class UserComponent implements OnInit {
  posts: Post[];
  constructor(private dataService: DataService) {}
  ngOnInit() {
    this.dataService.getPosts().subscribe((posts) => {
      console.log(posts.form);
      this.posts = posts;
      this.posts = posts.form;
    });
  }
}
interface Post {
  userId: number,
  formId: string,
  form: any,
  id: any,
  caption: string,
  type: string,
  lastChangedDate: any,
  lastChangedBy: string
}

在user.component.html

<table>
  <tr>
    <th>id</th>
    <th>caption</th>
    <th>type</th>
  </tr>
  <tr *ngFor="let post of posts">
    <td>{{post.id}}</td>
  </tr>
</table>

如何将id、标题和类型取出并放入表格中?

【问题讨论】:

  • 请注意,这是指 Angular (2+) 而不是 AngularJS。 AngularJS 指的是具有不同语法的 1.x 版本。

标签: arrays json angular api


【解决方案1】:

我假设您已经在this.posts 中存储了表单对象,即:

this.posts = posts;
this.posts = posts.form;

现在只需遍历数组以获取 id、caption 和 type:

<table class="table">
<thead>
<th>id</th>
<th>caption</th>
<th>type</th>
</thead>
<tbody>
<tr *ngFor="let post of posts">
    <td>{{post.id}}</td>
    <td>{{post.caption}}</td>
    <td>{{post.type}}</td>
</tr>
</tbody>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 2021-06-14
    • 2019-11-30
    • 2023-03-29
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多