我在将.NET列表反序列化为Angular 2数组时遇到问题。我一直收到错误:
错误错误:无法找到不同的支持对象... NgFor仅支持绑定到诸如数组之类的Iterables。
我已经在这里查了一下,但提议的解决方案都没有为我工作: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 Developer Tool确认此控制器正确返回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>
对此有任何帮助将不胜感激
答案 0 :(得分:0)
答案非常简单。
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
我在列表上进行冗余序列化并将响应作为字符串传回。
更改上述方法更正了问题:
// GET api/values
[HttpGet]
public ActionResult Get() => new JsonResult(Filters);