【问题标题】:Get specific column from JSON file in Angular2从Angular2中的JSON文件获取特定列
【发布时间】:2018-12-06 02:43:31
【问题描述】:

当我必须使用在线 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>

任何帮助都会很棒

【问题讨论】:

    标签: javascript json angular typescript angular6


    【解决方案1】:
    <div>
    <button (click)="loadUser()">Load User</button>
    <div *ngIf="enable">
    <div *ngFor="let profile of _profile  "
        {{ profile | json }}
    </div>
    

    除了上面的答案,您仍然可以使用Json pipengFor

    【讨论】:

      【解决方案2】:

      你需要像这样遍历数组 -

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

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

      【讨论】:

        【解决方案3】:

        您需要使用 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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          • 2017-11-30
          • 1970-01-01
          • 2016-08-22
          • 2020-09-16
          相关资源
          最近更新 更多