gpt4 book ai didi

javascript - 如何在 Angular 4 中过滤 JSON 数据

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

我正在尝试在页面上填充数据,但是它没有在页面上呈现。相反,它会抛出一条错误消息:

core.es5.js:1020 ERROR SyntaxError: Unexpected token ' in JSON at position 322

question-card.component.ts

import { Component, OnInit } from '@angular/core';
import { RetrieveDataService } from '../retrieve-data.service';

@Component({
selector: 'app-question-card',
templateUrl: './question-card.component.html',
styleUrls: ['./question-card.component.css']
})
export class QuestionCardComponent implements OnInit {
question = '';
questions = [];
constructor(private retrieveDataService: RetrieveDataService) {
this.appendContent();
}

ngOnInit() {
}

appendContent(){
for (var i = 0; i < 5; i++) {
this.retrieveDataService.fetchData().subscribe(data=>{
if (data[i].type == "question-card") {
this.question = (data[i].question);
this.questions.push(this.question);
}
});
}
}
}

question-card.component.html

<div class="container" *ngFor="let question of questions">
<h3>{{question.section}}</h3>
</div>

检索数据.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class RetrieveDataService {
constructor(private http: Http) {
}
fetchData(){
return this.http.get('assets/page-content.json').map(
(response) => response.json()
)
}
}

页面内容.json

[
{
"id": 1,
"type": "question-card",
"section": "some text comes here...",
"headline": "some text comes here...",
"question": "some text comes here...?",
"options": ['<25%', '25-50%', '51-75%', '>75%'],
"notes": "some text comes here..."
},
{
"id": 2,
"type": "question-flipping-card",
"section": "some text comes here...",
"headline": "some text comes here...",
"options": ['<25%', '25-50%', '51-75%', '>75%']
}
]

最佳答案

如果您知道 json 的长度,您可以使用 let 而不是 varlet 将为该 block 范围的异步操作保留 i。如果您使用 var,那么 i 将是所有异步操作的最后一个值:

appendContent(){
this.retrieveDataService.fetchData().subscribe(data=>{
for (let i = 0; i < data.length; i++) {
if (data[i].type == "question-card") {
this.questioncard = data[i];
this.questionscard.push(this.questioncard);
}
}
});

}

}

html:

<div class="container" *ngFor="let q of questionscard">
<h3>{{q?.section}}</h3>
</div>

关于javascript - 如何在 Angular 4 中过滤 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45078744/

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