我正在尝试在HTML的选择选项中打印简单的休息消耗的json数据。 我做了很多次,但我无法弄清楚我在这里做错了什么。 我想使用ngOnIt,因为我必须在我的HTML之前加载我的国家和地区
HTML -
<b>
<div class="form-group">
<label for="country" class="cols-sm-2 control-label">Country</label>
<div class="cols-sm-10">
<div class="input-group" *ngIf="loc">
<span class="input-group-addon"><i class="fa fa-globe fa" aria-hidden="true"></i></span>
<select class="form-control" name="1" id="1" style="color:#000;">
<option value=""selected>Select Country</option>
<option *ngFor="let a of loc" value="{{a.CountryId}}">{{a.CountryName}}</option>
</select>
</div>
</div>
</div>
</b>
我的组件 -
`import { Component, OnInit, Input, Pipe, NgModule } from '@angular/core';
import { resetFakeAsyncZone } from '@angular/core/testing';
import{HttpClient, HttpParams, HttpHeaders} from'@angular/common/http';
import { Http } from '@angular/http/src/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkjoin';
import { forkJoin } from 'rxjs/observable/forkJoin';
import { ReactiveFormsModule,FormsModule,FormGroup,FormControl,Validators,FormBuilder } from '@angular/forms';
export class AppComponent implements OnInit {
loc : any;
constructor( private http:HttpClient) {}
ngOnInit(){
this.http.get('http://localhost:50749/api/TravelDetails/Get/Locations?type=json')
.subscribe((json)=>{this.loc = json; console.log(this.loc);});
};`
json api消耗的数据,在XHR以及控制台结果中完美显示 -
[
[{
"States": [{
"StateId": 1,
"Country_Id": 1,
"StateName": "Alabama"
}, {
"StateId": 50,
"Country_Id": 1,
"StateName": "Wyoming"
}],
"CountryId": 1,
"CountryName": "United States of America",
"CountryCode": "USA"
}, {
"States": [{
"StateId": 51,
"Country_Id": 2,
"StateName": "Alberta"
}, {
"StateId": 63,
"Country_Id": 2,
"StateName": "Yukon"
}],
"CountryId": 2,
"CountryName": "Canada",
"CountryCode": "CA"
}]
]
答案 0 :(得分:0)
据我了解您的问题,您需要在您的#ngFor
中添加异步管道<option *ngFor="let a of loc | async" value="{{a.CountryId}}">{{a.CountryName}}</option>
以便在ngOnInit上显示您的信息
答案 1 :(得分:0)
尝试这个,它应该工作
<option *ngFor="let a of loc"
[value]="a.CountryId"
">
{{a.CountryName}}
</option>