簡體   English   中英

Angular4:從Json加載數據

[英]Angular4: Load data from Json

我是Angular的新手。 我正在做的是在點擊時從json文件加載數據,到目前為止我已經正確完成了。

但是我遇到的問題是在點擊之前加載第一個json對象,即在頁面加載時加載第一個對象

打字稿

export class RequestComponent{
  people: Object[];
  constructor(http:Http){
    http.get('data.json').subscribe(res => {
      this.people = res.json();
    });
  }

  public currentStatus;
  public setThis = (people) => this.currentStatus = people;
}

HTML

  <ul class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
      <span><i class="fa fa-cog" aria-hidden="true"></i></span>
      <p>{{ person.name }}</p>
    </li>
  </ul>
   <div *ngIf="currentStatus" class="col-md-8 right-section">
      <h2>{{ currentStatus.name }}</h2>
      <img [src]="currentStatus.img" class="img-responsive"/>
   </div>

嘗試在ngOnInit()函數中加載json。

import { Component, OnInit } from '@angular/core';
// other imports

export class RequestComponent implements ngOnInit{
  people: Object[];

  constructor(private http:Http){}

  ngOnInit(){
      this.http.get('data.json').subscribe(res => {
      this.people = res.json();
    });
  }
}

並添加ngIf用於顯示您的記錄,因此它不會嘗試在加載people之前顯示它。

<ul *ngIf="people" class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
        <span><i class="fa fa-cog" aria-hidden="true"></i></span>
        <p>{{ person.name }}</p>
    </li>
</ul>
<div *ngIf="currentStatus" class="col-md-8 right-section">
    <h2>{{ currentStatus.name }}</h2>
    <img [src]="currentStatus.img" class="img-responsive" />
</div>

您的頁面加載速度通常比從API獲得響應的速度快,因此您應該在獲得響應后設置訂閱者內部的人員,這樣您就可以確定它已經收到了響應。

constructor(private http:Http){
    this.http.get('data.json').subscribe(res => {
        this.people = res.json();
        if(this.people && this.people.length>0)
            this.setThis(this.people[0]);
    });
}

根據您的實現,執行if可能更合適,以確保在setThis中people數組不為空。


或者,你可以改變你的html

<ul class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
        <span><i class="fa fa-cog" aria-hidden="true"></i></span>
        <p>{{ person.name }}</p>
    </li>
</ul>
<div *ngIf="currentStatus>-1" class="col-md-8 right-section">
    <h2>{{ people[currentStatus]?.name }}</h2>
    <img [src]="people[currentStatus]?.img" class="img-responsive"/>
</div>

將currentStatus更改為一個數字,並將其默認為0.這將允許您在html更新時立即避免將currentStatus分配給第一個人的問題。 如果您需要禁用currentStatus部分的顯示,只需將其設置為-1即可。

的? 在.name和.img之前告訴html在嘗試訪問名稱或img之前驗證對象是否存在,如果它不存在則不顯示該部分。

嘗試這個:

constructor(private http:Http){
    this.http.get('data.json').subscribe(res => {
        this.people = res.json();
    });
}

ngAfterViewInit(){        
    this.setThis(this.people[0]);
}

暫無
暫無

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

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