user6680 user6680 - 1 month ago 13
JSON Question

Outputting JSON to page

I'm having issues outputting JSON data to the page.
I can output the JSON Objects to the console using console.log, but not the page using angular.
I'm still new at this. Can anyone point on where I went wrong.

Error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.


post.service.ts

import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import {Injectable} from "@angular/core";
import {Post} from './post';

@Injectable()
export class PostService{

constructor(private _http:Http){


}
getPosts(){
return this._http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());

}
}


app.component.ts

import { Component } from '@angular/core';
import {PostService} from './post.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [PostService]
})
export class AppComponent {
private posts;

constructor(private _postService:PostService){
this.posts =_postService.getPosts();


}
}


app.component.html

<h1>
<ul>
<li *ngFor="let post of posts">
{{post.title}}
</li>

</ul>
</h1>


post.ts

export class Post{
id?: number;
body: string;
title: string;


}

Answer

You need to subscribe to your http request to get data and display it, you are currently trying to iterate through Observable, which is impossible. You should also use OnInit instead of constructor:

import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [PostService]
})

export class AppComponent {

private posts;

constructor(private _postService:PostService) {}

ngOnInit() {
    this._postService.getPosts().subscribe(
    (res) => {
     this.posts = res; <--
     });
}

}

Here's nice article about http requests with Observables, it has examples too.