gpt4 book ai didi

javascript - 无法在 *ngFor 中呈现数据,但它已经以 Angular 7 显示在控制台中

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:41 24 4
gpt4 key购买 nike

我正在尝试呈现从 API 获取的数据以在我的 html 页面中显示它。但是,即使在我使用 console.log()

时它已经显示,我也无法将数据呈现到我的 html 页面

我已经尝试了这个主题的一些答案,但它仍然没有解决我的问题:

I am getting Data in Console Using Angular but I can't render it in html

Angular - How ngFor works?

这是我的 body.component.ts:

import { Component, OnInit } from '@angular/core';
import { TimelineService } from 'src/app/services/timeline.service';

@Component({
selector: 'app-body-homepage',
templateUrl: './body.component.html',
styleUrls: ['./body.component..scss']
})
export class BodyComponent implements OnInit {

constructor(public timeline: TimelineService) { }

ngOnInit() {
this.getTimeline();
}

getTimeline(){
this.timeline.timeline().subscribe((data)=>{
let timelines = [];
let i;

for (i=0; i < data.timelines.length; i++) {
let id = data.timelines[i]._id;
let date = data.timelines[i].date;
let title = data.timelines[i].title;

timelines.push({"id": id, "date": date, "title": title})
}
console.log("Cek Timelines : ", timelines);
});
}

scrollToElement($element): void {
console.log($element);
$element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
}

这是控制台中的响应数据:

[{
"_id": "5ce8122d7e55260d3d9dd78a",
"title": "Kumpul Perdana",
"body": "Kumpul Perdana MPKMB 56",
"date": "2019-08-29T17:00:00.000Z",
"__v": 0
},
{
"_id": "5ce812b27e55260d3d9dd78b",
"title": "Pembagian Kelompok Besar",
"body": "Pembagian Kelompok Besar",
"date": "2019-09-15T17:00:00.000Z",
"__v": 0
}
]

这是我的html代码:

<div class="row">
<div class="col-12 col-md-12 col-lg-12">
<ul>
<li *ngFor="let item of timelines">
{{item.date}}. {{item.title}}
</li>
</ul>
</div>
</div>

但是当我尝试正常使用数据而不使用像这样的 API 时:

问题:

items = [{
"_id": "5ce8122d7e55260d3d9dd78a",
"title": "Kumpul Perdana",
"body": "Kumpul Perdana MPKMB 56",
"date": "2019-08-29T17:00:00.000Z",
"__v": 0
},
{
"_id": "5ce812b27e55260d3d9dd78b",
"title": "Pembagian Kelompok Besar",
"body": "Pembagian Kelompok Besar",
"date": "2019-09-15T17:00:00.000Z",
"__v": 0
}
]

html:

<div class="row">
<div class="col-12 col-md-12 col-lg-12">
<ul>
<li *ngFor="let item of items">
{{item.date}}. {{item.title}}
</li>
</ul>
</div>
</div>

一切正常

有人可以帮我解决这个问题吗?我觉得我错过了解决它的东西,但我无法弄清楚问题是什么

最佳答案

在组件的顶部声明时间线,

timelines = [];

然后,

this.timelines.push({"id": id, "date": date, "title": title})

在方法中使用 let 将使您的变量仅可用于该方法。

关于javascript - 无法在 *ngFor 中呈现数据,但它已经以 Angular 7 显示在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313400/

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