显示来自json对象数组的数据

时间:2016-11-10 13:50:58

标签: json loops angular angular-services

我无法遍历json对象数组并在单独的div中显示所有数据。 目前只使用一些模拟数据。

Team.servie.ts:

<?php 
//Try this code in function.php file

//set cookie 
add_action( 'init', 'setCookie' );
function setCookie() {
setcookie( 'my-name', 'my-value', time() + 3600, COOKIEPATH, COOKIE_DOMAIN   );
}

//get Cookie 
add_action( 'wp_head', 'getCookie' );
function getCookie() {
$cookie_val = isset( $_COOKIE['my-name'] ) ? $_COOKIE['my-name'] : 'not set';
}

//Delete / Unset Cookie
add_action( 'init', 'unsetCookie' );
function unsetCookie() {
setcookie( 'my-name', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );
}
?>

Component.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());
    }
}

Team.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]);
                });
            }
}

component.html:

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

我知道我错过了什么,但我无法弄清楚是什么。

任何提示都将不胜感激。

1 个答案:

答案 0 :(得分:2)

使用* ngFor结构指令,如:

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

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

</div>
相关问题