【发布时间】:2017-07-25 06:54:21
【问题描述】:
我一直在尝试各种从 API 获取数据并使用ngFor 将其显示在列表中。我已经尝试过承诺、可观察和使用地图、订阅、异步管道,但还没有运气。我确定 API 已被命中,但由于某种原因,它要么显示空白数据,要么引发不同的错误。我最近得到的是
尝试比较 '[{"id":1,"name":"Bike 1"},{"id":2,"name":"Bike 时出错 2"},{"id":3,"name":"自行车 3"}]' 在 DefaultIterableDiffer.diff..
我有一种预感,该函数没有返回 ngFor 所期望的数组。
以下是我的 add-bike.component.ts
import { Component, OnInit } from '@angular/core';
import { Bike } from "./Entity/bike";
import { BikeService } from "./bike.service";
@Component({
selector: 'add-bike',
template : `<p>Hello</p><ul>
<li *ngFor="let bike of bikes">
{{ bike.name}}
</li>
</ul>`
})
export class AddBikeComponent implements OnInit {
bikes: Bike[] = [];
errorMessage: string;
constructor(private bikeService: BikeService) {
}
ngOnInit(): void {
this.bikeService.getRequest().subscribe(res => this.bikes = res);
}
}
bike.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Bike } from './Entity/bike';
@Injectable()
export class BikeService {
private _url = 'api/bikes';
constructor(private http: Http) { }
getRequest() {
return this.http.get(this._url).map(res => res.json());
}
}
bike.ts
export class Bike {
id: number;
name: string;
}
C# 中的 Web API 代码:
public class Bike
{
public int id { get; set; }
public string name { get; set; }
}
public IHttpActionResult Get()
{
List<Bike> list = new List<Bike>();
list.Add(new Bike() { id = 1, name = "Bike 1" });
list.Add(new Bike() { id = 2, name = "Bike 2" });
list.Add(new Bike() { id = 3, name = "Bike 3" });
return Ok(JsonConvert.SerializeObject(list));
}
API 响应:api/bikes
"[{\"id\":1,\"name\":\"Bike 1\"},{\"id\":2,\"name\":\"Bike 2\"},{\"id\":3,\"name\":\"Bike 3\"}]"
【问题讨论】:
-
你能发布
Bike的打字稿定义吗? -
您可以尝试显示
bikes而不是*ngForing 吗?只需{{bikes}},让我们知道显示的内容。也可以试试{{bikes|json}} -
您是否尝试过使用
interface而不是class。通常,我们将interfaces用于“模型对象”。 -
@Amit {{bikes}} 什么也没显示。
-
添加 json.parse() 后它工作了。 @Amit
标签: c# angular asp.net-web-api