gpt4 book ai didi

angular - 在 Angular 组件中显示 JSON 数据

转载 作者:行者123 更新时间:2023-12-01 11:16:07 25 4
gpt4 key购买 nike

我有一个从服务器获取数据的服务

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 上显示的数据

但是网站上没有显示数据:

应用组件.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

最佳答案

ngFor 需要一个用于循环的数组。作为对象的响应。使 carddata 成为一个数组并推送响应对象。

  private cardData: any = [];

constructor(private svc: CardService) { }

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

关于angular - 在 Angular 组件中显示 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50967414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com