【问题标题】:How to filter JSON data in angular 4如何过滤 Angular 4 中的 JSON 数据
【发布时间】:2017-07-14 02:25:57
【问题描述】:

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

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>

retrieve-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()
      )
  }
}

页面内容.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 中使用 " 而不是 '。
  • 您在 for 循环中的 i 在您的订阅回调中始终为 4。而且由于您的 json 现在没有data[4],因此它将是未定义的。
  • @echonax 你能用例子进一步解释一下吗?
  • @RahulDagli 如果您使用的是subscribe,那么这是一个异步操作。异步操作需要时间才能完成。为简单起见,本示例假设为 100 毫秒。当i=0 触发此请求时,代码将需要 100 毫秒才能进入订阅块。当它确实落入订阅块(100 毫秒后)时,你的 for 循环就已经完成了。因为在 100 毫秒内,for 循环甚至可以遍历安全的最大整数值。因此,对于所有 5 个 fetchData 请求,您的 i 将是 for 循环中的最大值。检查这个:jsfiddle.net/dyyad3nd
  • @echonax,感谢您的解释。那么在 Async 操作中循环而不是 for 循环的首选方式是什么?

标签: javascript angular typescript


【解决方案1】:

如果您知道 json 的长度,您可以使用 let 而不是 varlet 将为该块范围的异步操作保留 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>

【讨论】:

  • 更新到这个之后。当我做console.log(this.questions); 它输出空数组?
  • @RahulDagli 请更具体一点 :-) 你在哪里 console.log(this.questions);?
  • 下方for(){...}
  • @RahulDagli 我认为您不知道异步操作在 javascript 中是如何工作的。我已经告诉过你异步操作需要大约 100 毫秒~ 时间才能完成。当fetchData 完成它的工作时,您的console.log 已经被打印出来了。在subscribe 回调中写下你的console.log。我会更新我的答案。
  • 是的。现在我的最后一个查询是页面上没有呈现数据。
【解决方案2】:

更新

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

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

  1. 像这样设置新值

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

  2. 或使用Observable 模式

试试这个

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

阅读更多sample here


原答案

在您的 json 文件中。

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

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

' 替换为"


来自www.json.org

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

【讨论】:

  • 你有这个答案的来源吗?
  • 谢谢,那个错误信息消失了,但现在我又收到一个错误ERROR TypeError: Cannot read property 'type' of undefined
  • appendContent 函数对循环进行了 5 次硬编码,但您的 json data.length 为 2,导致索引超出范围时 data[i] 未定义
  • 如果我将值 i 更改为 1 错误消失但页面上仍然没有呈现数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多