我正在学习Angular,我从Visual Studio中的示例项目Angular5TF1开始。示例中有一个菜单选项,称为“获取数据”,它模拟从服务器检索数据。我复制了此方法及其类和页面,并试图使其从我编写的方法中检索数据-它不起作用。
我从示例中复制了“ FetchData”方法及其类和页面,并试图使其从我编写的方法中检索数据。返回值显示正确的值,但是当我尝试显示数组中的值之一时,它返回未定义的值。另外,我返回10个值,for循环打印10行,但它们都是空白。有人可以解释原因并帮助我完成这项工作吗?预先感谢。
来自组件html:
<h1>Interests</h1>
<div class="col-lg-12"> </div>
<div class="col-lg-10">
Interest: <input type="text" id="txtInterest" /> <button (click)="test()">Add...</button>
</div>
<div class="col-lg-12"> </div>
<div class="col-lg-12"> </div>
<div class="col-lg-12">
<p *ngIf="!personalInterests"><em>Loading Interests, Please Wait...</em></p>
</div>
<table class='table' *ngIf="personalInterests">
<thead>
<tr>
<th>Interest Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let interest of personalInterests">
<td>{{ interest.InterestName }}</td>
</tr>
</tbody>
</table>
来自组件
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
//import { forEach } from '@angular/router/src/utils/collection';
@Component({
selector: 'interests',
templateUrl: './interests.component.html'
})
export class InterestsComponent {
public personalInterests: PersonalInterest[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + 'api/Interest/Interests').subscribe(result => {
this.personalInterests = result.json() as PersonalInterest[];
}, error => console.error(error));
}
public test() {
alert(this.personalInterests[1].InterestName);
}
}
interface PersonalInterest {
InterestName: string;
}
Aaaaa和控制器中的
[Route("api/[controller]")]
public class InterestController : Controller
{
[HttpGet("[action]")]
public IEnumerable<Interest> Interests()
{
var rng = new Random();
IEnumerable<Interest> PersInt = Enumerable.Range(1, 10).Select(index => new Interest
{
InterestName = string.Format("Test_{0:00}", index)
});
//To simulate a slow connection
System.Threading.Thread.Sleep(2000);
return PersInt;
}
public class Interest
{
public string InterestName { get; set; }
}
}
答案 0 :(得分:0)
使用驼峰案例解决了该问题。