0

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\"}]"
7
  • Can you post the typescript definition of Bike ? Commented Jul 25, 2017 at 6:56
  • Can you try displaying bikes instead of *ngForing it? just {{bikes}} and let us know what's displayed. Maybe try {{bikes|json}} too Commented Jul 25, 2017 at 6:58
  • Did you try by using by using interface instead of class. Usually, we use interfaces for "model objects". Commented Jul 25, 2017 at 7:00
  • @Amit {{bikes}} shows up nothing. Commented Jul 25, 2017 at 7:01
  • 1
    It worked after adding json.parse(). @Amit Commented Jul 25, 2017 at 7:11

3 Answers 3

1

If WebApi returns a class type, you don't have to use JsonConvert.SerializeObject.

I didn't try this together with the rest of your code, but probably changing your return method to this might work;

return Ok(list);
Sign up to request clarification or add additional context in comments.

1 Comment

You are absolutely right. I somehow overlooked this.
1

What you are getting from your response is in format that you currently need to parse to JSON, you can do it by adding a second map:

getRequest() {
    return this.http.get(this._url)
      .map(res => res.json())
      .map(res => JSON.parse(res))
}

DEMO: http://plnkr.co/edit/onfdvVmoCO3DVqgXn9cz?p=preview

2 Comments

Thank's a lot. I had a hunch that I'd need to parse it. But I was not able to figure out where to put json.parse(). Also, Could you add what changes I need to do to avoid json parsing,
I'm not familiar with C# unfortunately, but try what @coni2k suggested. The underlying problem is how you are sending the data from the backend. You need to send it as JSON string without the slashes like [{"someprop":"propValue", ....}], then you don't need to parse it.
1

bike.service.ts

getRequest() {
        return this.http.get(this._url).map(res => res.json() as  Bike[]);
    }

Make sure of Bike Entity

export class Bike {
    id: number;
    name: string;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.