我有点困惑。
我有一个正在使用的 API: https://api.myjson.com/bins/1gb9tf
这里还有一个 Angular 分量:
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 中的对象数组
祝你有美好的一天!
最佳答案
您需要使用嵌套的 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>
关于angular - 从 Angular 4 中的 API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123811/