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

时间:2017-09-21 10:56:09

标签: javascript html json angular

我想将json文件加载到所描述的表中。我尝试过但它不起作用。所有页面都附有此问题。表格没有显示在我的localhost中......我会做什么......提前谢谢。

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>
&#13;
&#13;
&#13;

app.component.ts

&#13;
&#13;
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);
  }
}
&#13;
&#13;
&#13;

json.services.ts

&#13;
&#13;
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'));
  }
}
&#13;
&#13;
&#13;

people.json

&#13;
&#13;
[
    {
        "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"
    }
]
&#13;
&#13;
&#13;

请告诉我如何提前......谢谢..

1 个答案:

答案 0 :(得分:0)

Angular建议Observable属性以&#34; $&#34;结尾。 所以你的组件会有:

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>