从Angular 4中的API获取数据

时间:2018-01-06 02:45:44

标签: angular http

我有点腌菜。

我有一个我正在使用的API: https://api.myjson.com/bins/1gb9tf

和角度分量:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  results: string[];



  // Inject HttpClient into your component or service.
 constructor(private http: HttpClient) {}

 ngOnInit(): void {
   // Making the HTTP Request
   this.http
    .get('https://api.myjson.com/bins/1gb9tf')
    .subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
      console.log(data);
    })
 }

  title = 'app';
}

,html为:

<!-- Search Form -->
<form class="" action="index.html" method="post">

  <h1> Let's Go. </h1>
  <hr>

  <select class="" name="">
    <option value="">Select means of Travel</option>
    <option value="">Flight</option>
  </select>

  <label for="Travel Start Date">Travel Start Date</label>
  <input type="date" name="" value="Travel Start Date">

  <label for="Travel End Date">Travel End Date</label>
  <input type="date" name="" value="Travel End Date">

  <select class="" name="">
    <option value="">Departure Location</option>
    <option value="">Atlanta</option>
  </select>

  <select class="" name="">
    <option value="">Arrival Location</option>
    <option value="">San Francisco</option>
  </select>

  <select class="" name="">
    <option value="">Product Class</option>
    <option value="">Economy</option>
  </select>

  <input style="width: 100px; background-color: green; color: #eef; height: 40px; border-radius: 50px; margin: 0 auto; margin-top: 50px;"
         type="submit" name="" value="Submit">

</form>

<!-- Results -->

<div class="result">
  {{ results }}
</div>

我基本上是尝试从API中提取数据,并将其显示在输入字段中,等等。大多数情况下,我只需要帮助循环遍历api

中的对象数组

祝你有美好的一天!

2 个答案:

答案 0 :(得分:4)

您需要使用嵌套的ngFor在页面上显示结果,您的结果有两个名为searchCriteria的对象和结果,您需要按如下方式循环结果,

 <ul>
    <li *ngFor="let group of displayItems">
    {{group.departure.city}}
    <ul>
        <li *ngFor="let flight of group.segments">
        {{flight.flightNumber}}
        </li>
    </ul>
    </li>
</ul>

DEMO

答案 1 :(得分:1)

你能澄清一下你挣扎的确切位置吗?您是否建议您在客户端获取有效负载,但需要帮助提取和解析数据?

您似乎走在正确的轨道上,但只是想确保我们在开始之前就在同一页面上。