简体   繁体   English

使用angular2将json数据加载到表中

[英]load json data into table with angular2

i want to load the json file into the table described. 我想将json文件加载到所描述的表中。 I tried it but it will not work . 我试过了,但是不起作用。 All the pages are attached with this question. 所有页面均附有此问题。 table does not shows in my localhost..what will i do ...thanks in advance. 该表未在我的本地主机中显示。.我该怎么办...谢谢。

app.component.html 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 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 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 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" } ] 

Please tell me how to perform..thanks in advance.. 请提前告诉我如何表演。

Angular suggests that Observable properties end with "$" so your component would have: Angular建议Observable属性以“ $”结尾,因此您的组件应具有:

data$: Observable<Array<any>>;

And in your template: 在您的模板中:

<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