簡體   English   中英

使用angular2將json數據加載到表中

[英]load json data into table with angular2

我想將json文件加載到所描述的表中。 我試過了,但是不起作用。 所有頁面均附有此問題。 該表未在我的本地主機中顯示。.我該怎么辦...謝謝。

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": "a@b.com", "age": "25" }, { "id": "2", "name": "efg", "email": "a@b.com", "age": "22" }, { "id": "3", "name": "hij", "email": "a@b.com", "age": "29" } ] 

請提前告訴我如何表演。

Angular建議Observable屬性以“ $”結尾,因此您的組件應具有:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM