【发布时间】:2018-04-20 10:23:32
【问题描述】:
我正在尝试将一些 JSON 数据从我的 API 绑定到 HTML,并在角度 4 中使用 *ngFor 对其进行迭代。不幸的是,我在这个问题的标题中遇到了错误。
有问题的代码:
countryList.ts
export interface CountryList {
UserName : string,
Country : string[],
}
Service.ts
export class LoginServicesService {
constructor(private o:Http) { }
functionCountriesList(userName:string)
{
return this.o.get('http://localhost:55760/api/Login/GetCountries/'+userName).map((res:Response) =><CountryList[]>res.json());
}
}
Component.ts
export class LoginComponent implements OnInit {
constructor(private loginService: LoginServicesService) { }
ngOnInit() {
}
countries: CountryList[];
countryValue: number;
countryName: string;
GenerateCountries(userName: string) {
this.loginService.functionCountriesList(userName).subscribe((data) => this.countries = data);
console.log(this.countries);
}
}
Component.HTML
<table align="center">
<tr>
<td><label id="lblUserName">UserName:</label></td>
<td><input #userName type="Textbox" id="txtUserName" (keyup.enter)="GenerateCountries(userName.value)" (blur)="GenerateCountries(userName.value)" /></td>
</tr>
<tr>
<td>
<label id="lblPassword">Password:</label>
</td>
<td><input type="password" id="txtPassword"/></td>
</tr>
<tr>
<td>Domain:</td>
<td>
<select id= "district" style="width:100%" (change)="selectdrop($event)">
<option value="NIL">Select Domain</option>
<option *ngFor="let c of countries;let i=index">{{c}}</option>
</select>
</td>
</tr>
</table>
来自 api 的 JSON 是
{
"UserName": "hello",
"Country": [
"South Africa",
"Russia",
"India",
"America",
]
}
【问题讨论】: