typescript 如何在 Angular 4 中过滤 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45078744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:42:48  来源:igfitidea点击:

How to filter JSON data in angular 4

javascriptangulartypescript

提问by Rahul Dagli

I'm trying to populate data on the page however, it's not getting rendered on the page. Instead its throwing an error msg:

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

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

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

question-card.component.ts

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

question-card.component.html

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

retrieve-data.service.ts

检索-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()
      )
  }
}

Page-content.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%']
    }
]

回答by eko

If you know the length of your json you can use letinstead of var. letwill preserve the ifor that block scoped async operation. If you use var, then iwill be the last value for all of your async operations:

如果你知道你的JSON的长度,你可以使用let的替代varlet将保留该i块范围的异步操作。如果使用vari则将是所有异步操作的最后一个值:

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:

html:

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

回答by aifarfa

updated

更新

first thing first, you actually calls service many times. mapand subscribealready iterate through response data, you don't need that for loop.

首先,您实际上多次调用服务。map并且subscribe已经遍历响应数据,您不需要那个 for 循环。

secondly, Angular will not updates HTML after Array mutation (Array.pushor shift) you can either..

其次,Angular 不会在 Array 突变(Array.pushshift)之后更新 HTML,您也可以..

  1. set new value like this

    this.questions = [...this.questions, this.question]

  2. or use Observablepattern

  1. 像这样设置新值

    this.questions = [...this.questions, this.question]

  2. 或使用Observable模式

try this

试试这个

  appendContent() {
    this.retrieveDataService.fetchData() 
      .filter((item) => item.type === 'question-card') 
      .subscribe(data => {
        this.questions = [...this.questions, data]
      });
  }

read more sample here

在此处阅读更多示例



original answer

原答案

in your json file.

在你的 json 文件中。

{
 // .. 
 "options": ['<25%', '25-50%', '51-75%', '>75%'],
}

single quote 'is not valid JSON format

单引号'不是有效的 JSON 格式

replace 'with "

替换'"



from www.json.org

来自www.json.org

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

值可以是双引号中的字符串、数字、真假或空值、对象或数组。这些结构可以嵌套。