I have been trying various to fetch data from API and to show it in a list using ngFor. I have tried promises, observable and played around with map, subscribe, async pipe but no luck yet. I am certain the API has been hit but for some reason, it either shows blank data or throws different errors. The most recent I've got is
Error trying to diff '[{"id":1,"name":"Bike 1"},{"id":2,"name":"Bike 2"},{"id":3,"name":"Bike 3"}]' at DefaultIterableDiffer.diff..
I have a hunch that the function isn't returning an array which is expected by ngFor.
Following is my 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;
}
Web API code in C#:
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 response: api/bikes
"[{\"id\":1,\"name\":\"Bike 1\"},{\"id\":2,\"name\":\"Bike 2\"},{\"id\":3,\"name\":\"Bike 3\"}]"
Bike?bikesinstead of*ngForing it? just{{bikes}}and let us know what's displayed. Maybe try{{bikes|json}}toointerfaceinstead ofclass. Usually, we useinterfacesfor "model objects".