【发布时间】: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