0
我有問題反序列化.NET列表到Angular 2數組中。我不斷收到一個錯誤:角2不反序列化.NET列表<T>
錯誤錯誤:無法找到不同的支持對象... 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);
}
我已經證實了這兩個郵遞員,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;
}
服務(過濾器.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(過濾器));'我敢肯定,你的結果是不是數組 – yurzui
@yurzui。你讓我回答,謝謝。當我登錄typeof時,我注意到它是一個字符串;所以我在res.json()周圍添加了JSON.Parse()。它看起來非常粗糙,但它現在正在工作。 –
@WashingtonGuedes;就是這樣。謝謝;這是多了,更清潔。 –