【发布时间】:2018-07-11 19:08:21
【问题描述】:
我正在尝试在我的 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);});
};`
api消耗的json数据,完美的显示在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"
}]
]
【问题讨论】:
-
你需要做什么,你有什么问题?请更新
-
使用本地自行创建的 rest API 和 json 结果来自我的 XHR 结果,我有一个选择框,我想在其中呈现我的“CountryName”作为选择国家/地区的选项。
-
我理解那部分,但你得到什么错误?在这里,您在一个组件中请求。您必须创建一个服务并将其作为组件的构造函数注入,我认为这就是您错过的。
-
我知道我没有使用最佳实践,但问题是昨天我已经实现了它,但我使用的是单组件单 html 和一个混乱的 Json,它带来了我所有的数据库,今天我已经简化了创建差异获取响应并在 1 个响应中获取国家/地区城市列表的事情,还有 1 个事情,我正在使用一个包含许多路线和组件的多步骤向导,它是一个 SPA。但我现在在我的应用控制器中工作,而不是在其他人中。
标签: json rest angular5 ngfor ngoninit