从 Angular 4 的 API 获取数据

Edd*_* II 3 http angular

我有点酸酸的。

我有一个正在使用的 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';
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

祝你有美好的一天 !

Saj*_*ran 5

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

 <ul>
    <li *ngFor="let group of displayItems">
    {{group.departure.city}}
    <ul>
        <li *ngFor="let flight of group.segments">
        {{flight.flightNumber}}
        </li>
    </ul>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

演示