Ruday Ruday - 29 days ago 9
AngularJS Question

Display data from a json object array

I am unable to loop through a json object array and display all data in separate divs.
Currently just using some mock data.

Team.servie.ts:

import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Team } from './team';

@Injectable()
export class TeamService {
private _url = "http://jsonplaceholder.typicode.com/posts"
constructor(private _http: Http){

}

getPost() : Observable<Team[]>{
return this._http.get(this._url)
.map(res => res.json());
}

createPost(post: Team){
return this._http.post(this._url, JSON.stringify(post))
.map(res => res.json());
}
}


Component.ts:

import { Component, OnInit } from '@angular/core';
import { TeamService } from '../team.service';


@Component({
selector: 'About',
templateUrl: './about.component.html',
providers: [TeamService]
})
export class AboutComponent implements OnInit{

data;


isLoading = true;

constructor(private _teamService: TeamService){
/*this._teamService.createPost({userId: 1, title: "a", body: "b"});*/
}

ngOnInit(){

var text = "";
var i = 0;

this._teamService.getPost()
.subscribe(post => {

this.isLoading = false;
this.data = post;
console.log(post[0]);
});
}
}


Team.ts

export interface Team{
userId: number;
id?: number;
title: string;
body: string;
}


component.html:

<div *ngIf="isLoading">Getting data....</div>


<div let displayData of data>

<p> {{ displayData.id }}</p>

</div>


I know I am missing something, but i can't figure out what.

Any tips would be greatly appreciated.

Answer

use the *ngFor structureal directive like:

<div *ngFor="let displayData of data">

    <p> {{ displayData.id }}</p>

</div>