2016-11-09 11 views
1

JSONデータをページに出力する際に​​問題があります。 console.logを使用してJSONオブジェクトをコンソールに出力できますが、角度を使用しているページは出力できません。 私はまだこれで新しいです。誰かが私が間違っていた場所を指摘できますか?JSONをページに出力する

エラー:

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> 
あなたは データを取得し、それを表示するようにHTTPリクエストにを購読する必要が

post.ts

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


} 

答えて

1

は、あなたが現在不可能である、Observableを反復処理しようとしています。またOnInitの代わり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; <-- 
    }); 
} 

} 

ここで、それはあまりにも例があり、観測とのHTTP要求についてarticleうれしいです。

+0

ありがとうございました。 – user6680

0

クラスPostServiceからのgetPostはオブジェクトではなく、Observableを返します。これを行う伝統的な方法は、戻り値を登録して割り当てることです。

this._postService.getPosts().subscribe(result => this.posts = result); 

また、make use of the async pipeとすることもできます。

this.posts$ = this._postService.getPosts(); 

また、HTMLテンプレートでは、非同期パイプを使用します。例えば:ところで

<span>{{ posts$ | async | json }}</span> 

、この基本的な動作は、Tour of Heroes (ToH)に非常に現実のアプリケーションに基づいて角度のための公式の「はじめに」のチュートリアルを議論してきました。