我正在从服务中的JSON获取数据。然后我在一个组件中调用该服务,我想将该值存储在某个变量中,并希望使用angular 6在下拉列表中发送这些值。
谢谢
您的组件应像这样:
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
public forecasts: WeatherForecast[];
public cacheForecasts: WeatherForecast[];
public summaries: any[];
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => {
this.forecasts = result;
this.cacheForecasts = result;
}, error => console.error(error));
http.get<any[]>(baseUrl + 'weatherforecast/GetSummaries').subscribe(result => {
this.summaries = result;
}, error => console.error(error));
}
filterForeCasts(filterVal: any) {
if (filterVal == "0")
this.forecasts = this.cacheForecasts;
else
this.forecasts = this.cacheForecasts.filter((item) => item.summary == filterVal);
}
}
interface WeatherForecast {
date: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
interface Summary {
name: string;
}
和这样的HTML文件:
<p>This component demonstrates fetching data from the server.</p>
<div>
<label>Summary: </label>
<select (change)="filterForeCasts($event.target.value)">
<option value="0">--All--</option>
<option *ngFor="let summary of summaries" value={{summary}}>
{{summary}}
</option>
</select>
</div>
<p *ngIf="!forecasts"><em>Loading...</em></p>
有关更多信息,请参见this