在Angular组件中显示JSON数据

时间:2018-06-21 11:26:01

标签: angular

我有一项正在从服务器获取数据的服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from "rxjs/Observable";

@Injectable()
export class CardService {

    private url = "http://192.168.100.112:8080/angular";

  constructor(private http: HttpClient) { }

  getCards(): Observable<any>{
  return this.http.get<any>(this.url);
 }
}

它与我的组件配合正常:

import { Component, OnInit } from '@angular/core';
import { CardService } from '../../services/card.service';

@Component({
    selector: 'cards-list',
    templateUrl: './card.component.html',
    styleUrls: ['./card.component.css']
  })
  export class CardComponent implements OnInit {

  private cardData: any;

  constructor(private svc: CardService) { }

  ngOnInit() {
    this.svc.getCards().subscribe(data =>{
      this.cardData = data;
      console.log(this.cardData)
    })
  }
}

控制台正在显示我要显示在app.component.html上的数据

但网站上未显示数据:

appcomponent.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <cards-list></cards-list>
</div>

card.component.html

<div *ngIf="cardData">
  <ul>
    <li *ngFor="let card of cardData">
       <span>{{card.name}}</span>
       <span>{{card.id}}</span>
       <span>{{card.progress}}</span>
       <span>{{card.issue}}</span>
    </li>
  </ul>
</div>

有人知道我在做什么错吗?

enter image description here

3 个答案:

答案 0 :(得分:3)

此代码不适用于单个对象。即使记录长度为1,也需要返回数组。

<div *ngIf="cardData">
  <ul>
    <li *ngFor="let card of cardData">
       <span>{{card.name}}</span>
       <span>{{card.id}}</span>
       <span>{{card.progress}}</span>
       <span>{{card.issue}}</span>
    </li>
  </ul>
</div>

答案 1 :(得分:2)

ngFor需要一个用于循环的数组。响应作为对象来。将carddata设置为数组并推送响应对象。

  private cardData: any = [];

  constructor(private svc: CardService) { }

  ngOnInit() {
    this.svc.getCards().subscribe(data =>{
      this.cardData.push(data);
      console.log(this.cardData)
    })
  }

答案 2 :(得分:-1)

定义私人卡数据:any [] = [];