How do you make an http get request that returns a json array which will be used to fill an ngfor directive?

Dan picture Dan · Jul 7, 2016 · Viewed 22.4k times · Source

I want to make an http get request that returns a json array of data that is to be used in an ngFor loop. I am not sure the best way to do this. this.list is the list to be looped through in the ngFor directive. For testing purposes, the json file is located on my local machine. I've looked through the Angular 2 documentation, as well as a udemy course for this, but can't figure it out. I suspect it is something simple.

The component with the ngFor directive.

constructor(private router:Router, private rec:RecommendationsService ){}
      ngOnInit(){
        this.rec.getRecommendations().subscribe(
          data=>{
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = this.x;
          }
        );
      }

The get request is located in a service

import 'rxjs/Rx';

@Injectable()
export class RecommendationsService{

  url="//Users/Daniel/Desktop/Reccomendations.json";

  constructor(private http:Http){};

  getRecommendations(){
    return this.http.get(this.url).map(res => res.json);
  }
}

This is the ngfor that needs the data.

 <div *ngFor="let item of list, let i = index" data-toggle="modal" data-target="#recModal">
                <div class="row rowTopBuffer rowDiv" (click)="toModal(item.name, item.description, item.recLocLat, item.recLocLong, item.picturePath)">
                    <div class="col-sm-12 col-md-4 titleDiv" >
                        <img class="recommendationImages img-responsive img-rounded" src={{item.picturePath}}>
                    </div>
                    <div class="col-sm-12 col-md-6 descDiv">

                    <p class="itemTitle">{{item.name}}</p>
                    <p id="{{desc+i}}">{{item.description}}</p>

                    </div>
                </div>
            </div>

Right now EXCEPTION: [object Object] is thrown in the console when running this code.

Answer

rinukkusu picture rinukkusu · Jul 7, 2016

Don't stringify that object again, since you can't loop through a string :)

ngOnInit(){
    this.rec.getRecommendations().subscribe(
        data => {
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = data;
        },
        error => console.log(error),
        () => console.log("done")
    );
}

Also in your service call the 'json()' method like this:

getRecommendations(){
    return this.http.get(this.url).map(res => res.json());
}

And in your template you have a faulty ngFor usage. Use ; instead of , to seperate the index.

*ngFor="let item of list; let i = index"