2017-09-21 78 views
0

我想將json文件加載到描述的表中。我嘗試過,但它不會工作。所有頁面都附有這個問題。表不顯示在我的本地主機..我會怎麼做...提前感謝。將json數據加載到帶有角度2的表格中

app.component.html

<h1> 
 
    hellooooooo {{title}} 
 
</h1> 
 
<div *ngFor="let d of data | async"> 
 
<table border="1"> 
 
<tr> 
 
    <th>ID:</th><th>name:</th><th>email:</th><th>age:</th></tr> 
 
    <tr><td>{{d.id}}</td><td>{{d.name}}</td><td>{{d.email}}</td><td>{{d.age}}</td></tr> 
 
</tr> 
 
</table> 
 
</div>

app.component.ts

import { Component } from '@angular/core'; 
 
import { Observable } from 'rxjs'; 
 
import { JsonService } from 'app/json.service'; 
 

 
@Component({ 
 
    selector: 'app-root', 
 
    templateUrl: './app.component.html', 
 
    styleUrls: ['./app.component.css'], 
 
    providers: [JsonService] 
 
}) 
 
export class AppComponent { 
 
    title = 'app works!'; 
 
    data: Observable<Array<any>>; 
 

 
    constructor(private service: JsonService){ 
 
    this.data = service.getpeople(); 
 
    console.log("AppComponent.data:" +this.data); 
 
    } 
 
}

json.services.ts

import { Injectable } from '@angular/core'; 
 
import { Http, Response } from '@angular/http'; 
 
import { Observable } from 'rxjs'; 
 

 
@Injectable() 
 
export class JsonService { 
 
    getpeople: any; 
 

 
    constructor(private http: Http) { } 
 
getPeople(): Observable<any>{ 
 
    return this.http.get('./data/people.json') 
 
    .map((res:Response) => res.json()) 
 
    .catch((error:any) => Observable.throw(error.json().error || 'server error')); 
 
    } 
 
}

people.json

[ 
 
    { 
 
     "id": "1", 
 
     "name": "abc", 
 
     "email": "[email protected]", 
 
     "age": "25" 
 
    }, 
 
    { 
 
     "id": "2", 
 
     "name": "efg", 
 
     "email": "[email protected]", 
 
     "age": "22" 
 
    }, 
 
    { 
 
     "id": "3", 
 
     "name": "hij", 
 
     "email": "[email protected]", 
 
     "age": "29" 
 
    } 
 
]

請告訴我如何提前perform..thanks ..

回答

0

角度表明,可觀察屬性結束w第i個 「$」 所以你的組件必須:

data$: Observable<Array<any>>; 

而且在你的模板:

<div *ngIf="data$ | async; let d"> 
    <table border="1"> 
     <tr> 
      <th>ID:</th> 
      <th>name:</th> 
      <th>email:</th> 
      <th>age:</th> 
     </tr> 
     <tr> 
      <td>{{d.id}}</td> 
      <td>{{d.name}}</td> 
      <td>{{d.email}}</td> 
      <td>{{d.age}}</td> 
     </tr> 
    </table> 
</div> 
相關問題