从 Angular2 中的 JSON 文件中获取特定列

Get specific column from JSON file in Angular2

当我必须使用在线 JSON 文件时,我现在正在处理 Angular2 项目。我使用 http.get 但我得到了所有文件,我只想要第二和第三列,first_name 和 last_name.

这是 JSON 文件 > http://alexgr.ro/ehealth/patients.json

这是我的代码

admin1.component.ts 我想在其中显示日期

import { Component } from '@angular/core';
import { UserService } from '../services/user.service';

@Component({
moduleId: module.id,
selector: 'admin1',
templateUrl: `admin1.component.html`,
})
export class Admin1Component  {
enable: boolean;
_profile: {}

constructor(private userService: UserService) {
    this.enable = false;
}

loadUser() {
    this.userService.getUser().subscribe(data => this._profile = data);
    this.enable = true;
 }
}

我的user.service.ts

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

@Injectable()
export class UserService {
constructor (private http: Http) {}

 getUser() {
 return this.http.get('http://alexgr.ro/ehealth/patients.json')
  .map((res:Response) => res.json());
 }
}

和我的admin1.component.html

<div>
<button (click)="loadUser()">Load User</button>
<div *ngIf="enable">
    {{ _profile | json }}
</div>

任何帮助都会很棒

您需要使用 ngFor 循环遍历项目,

<div>
<button (click)="loadUser()">Load User</button>
<div *ngIf="enable">
<ul>
    <li *ngFor="let pro of _profile ">
       <h1> {{ pro.first_name}} </h1>
       <h1> {{ pro.last_name}} </h1>
    </li>
  </ul>
</div>

您需要像这样遍历数组 -

<div *ngFor='let profile of _profile'>
    {{ profile.first_name }}     {{ profile.last_name }}
</div>

目前,您正在使用 json 管道,它只打印整个数据到 DOM。

<div>
<button (click)="loadUser()">Load User</button>
<div *ngIf="enable">
<div *ngFor="let profile of _profile  "
    {{ profile | json }}
</div>

除了上述答案之外,您还可以将 Json pipengFor 结合使用。