[英]How to filter JSON data in angular 4
我正在尝试填充页面上的数据,但是它没有在页面上呈现。 相反,它抛出一个错误消息:
core.es5.js:1020错误语法错误:JSON中位置322的意外令牌'
问题-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);
}
});
}
}
}
问题-card.component.html
<div class="container" *ngFor="let question of questions">
<h3>{{question.section}}</h3>
</div>
检索,data.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()
)
}
}
页面content.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
而不是var
。 let
将为块范围的异步操作保留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>
首先,您实际上多次致电服务。 map
和subscribe
已经通过响应数据进行迭代,您不需要for循环。
其次,在您可以进行Array突变( Array.push
或shift
)之后,Angular不会更新HTML。
像这样设置新值
this.questions = [...this.questions, this.question]
或使用可观察模式
尝试这个
appendContent() {
this.retrieveDataService.fetchData()
.filter((item) => item.type === 'question-card')
.subscribe(data => {
this.questions = [...this.questions, data]
});
}
在您的json文件中。
{
// ..
"options": ['<25%', '25-50%', '51-75%', '>75%'],
}
单引号'
是无效的JSON格式
将'
替换为"
值可以是带双引号的字符串,也可以是数字,也可以是true或false或null,或者是对象或数组。 这些结构可以嵌套。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.