【发布时间】:2017-08-30 04:32:13
【问题描述】:
我在将 .NET 列表反序列化为 Angular 2 数组时遇到问题。我不断收到错误消息:
ERROR 错误:找不到不同的支持对象...NgFor 仅支持绑定到可迭代对象,例如数组。
我已经检查过这里,但没有一个建议的解决方案对我有用:https://github.com/angular/angular/issues/6392
C#
型号
public class Filter
{
public string filterType { get; set; }
public string filterKey { get; set; }
public string filterValue { get; set; }
}
控制器动作
public List<Filter> Filters { get; set; } = new List<Filter>()
{
new Filter()
{
filterType = "TypeA",
filterValue = "ValueA",
filterKey = "TypeA|ValueA"
},
new Filter()
{
filterType = "TypeB",
filterValue = "ValueB",
filterKey = "TypeB|ValueB"
}
};
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
我已通过 POSTMAN 和 Chrome 开发工具确认此控制器正确返回 JSON:
[{"filterType":"TypeA","filterValue":"TypeA","filterKey":"TypeA|ValueA"},
{"filterType":"TypeB","filterValue":"ValueB","filterKey":"TypeB|ValueB"}]
角度
模型(filter.ts)
export class Filter{
filterType: string;
filterKey: string;
filterValue:string;
}
服务 (filter.service.ts)
@Injectable()
export class FilterService {
private apiUrl: string = "http://localhost:7639/api/filters";
constructor(private http: Http) { }
public getFilters = (): Observable<Filter[]> => {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.apiUrl,options)
.map(res => <Filter[]>res.json())
.do(x => console.log(x)) <-- This clearly logs the JSON
.catch(this.handleError);
}
private handleError(error:Response){
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
组件(filter.component.ts)
export class FilterComponent implements OnInit{
title = 'Filters';
public filters: Filter[];
constructor(private filterService: FilterService) {
}
ngOnInit() {
this.getFilters();
}
private getFilters(){
this.filterService.getFilters().subscribe(filters => {
this.filters = filters;
console.log(filters);
},
error => {
console.log(error);
}, () => {
});
}
}
组件 HTML (filter.component.html)
<h1>{{title}}</h1>
<div *ngFor="let filter of filters">
<p>{{filter.filterType}}</p>
<p>{{filter.filterValue}}</p>
<p>{{filter.filterKey}}</p>
</div>
如有任何帮助,我们将不胜感激
【问题讨论】:
-
试试
console.log(Array.isArray(filters));我确定你的结果不是数组 -
@yurzui。你引导我找到答案,谢谢。当我记录 typeof 时,我注意到它是一个字符串;所以我在 res.json() 周围添加了 JSON.Parse()。它看起来很恶心,但它现在可以工作了。
-
@WashingtonGuedes;就是这样。谢谢;那干净多了。
标签: json angular typescript asp.net-web-api asp.net-core