【发布时间】:2018-05-09 23:13:24
【问题描述】:
我已经尝试解决这个问题一段时间了,肯定可以使用一些帮助。 我正在尝试显示从服务器获得并存储在本地的问题。但是当我尝试显示我得到的问题时,它给了我以下错误:
Cannot read property 'question' of undefined
这是我的 HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questionnaire</title>
</head>
<body>
<div class="container" id="Question" align="center">
<h2 [innerHTML] = "q.question"></h2>
</div>
</body>
</html>
这是肯定会返回值的打字稿,因为我可以记录它们,所以我检查了:
@Component({
selector: 'app-new-questionnaire',
templateUrl: './new-questionnaire.component.html',
styleUrls: ['./new-questionnaire.component.css'],
providers: [NewServerRequestsService]
})
export class NewQuestionnaireComponent implements OnInit {
q: any;
sub: any;
id: number;
cQuestion: number;
score: number;
qNumber: number;
constructor(private serverService: NewServerRequestsService, private
route: ActivatedRoute, private router: Router){}
static questionTime = performance.now();
onload()
{
console.log(NewQuestionnaireComponent.questionTime);
// this.ButtonClicks();
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
// (+) converts string 'id' to a number
// fetch the file and get next Question
this.id = +params['id'];
if (localStorage.getItem('q') !== null) {
var data = JSON.parse(localStorage.getItem('q'))
this.qNumber = parseInt(localStorage.getItem('qNumber'))
this.q = data.results[this.id - 1]
} else {
this.serverService.getQuestion()
var data = JSON.parse(localStorage.getItem('q'))
this.qNumber = parseInt(localStorage.getItem('qNumber'))
this.q = data.results[this.id - 1]
}
});
}
}
}
这里是服务:
@Injectable()
export class NewServerRequestsService {
constructor(private http: Http) { }
getQuestion()
{
return this.http.get("https://opentdb.com/api.php?amount=30")
.map(res => res.json()).subscribe(
data => {
// shuffle questions
for (var i = 0; i < data.results.length - 1; i++) {
var j = i + Math.floor(Math.random() * (data.results.length -
i));
var temp = data.results[j];
data[j] = data.results[i];
data[j].incorrect_answers.push(data[j].correct_answer)
data[i] = temp;
}
localStorage.setItem("q", JSON.stringify(data))
localStorage.setItem("qNumber", JSON.stringify(data.length))
},
err => console.error(err)
)
}
}
这里是获取数据的地方:
@Component({
selector: 'home',
templateUrl: 'home.component.html',
providers: [NewServerRequestsService]
})
export class HomeComponent implements OnInit, OnDestroy {
constructor(private QuizService: NewServerRequestsService, private route:
ActivatedRoute, private router: Router) {
}
ngOnInit() {
this.QuizService.getQuestion();
}
ngOnDestroy() { }
}
【问题讨论】:
-
尝试删除所有非必要代码,以提供重现您的问题的最小示例。这样一来,人们就更有可能尝试帮助您,并且该问题对有类似问题的其他人也更有帮助。
-
您(至少)在模板和 TS 中遇到了一些异步问题。调用
this.serverService.getQuestion()时,您无法确定在获取数据时是否在localStorage 中设置了数据:var data = JSON.parse(localStorage.getItem('q'))在您的else中。我 99% 确定数据不存在。请阅读此:stackoverflow.com/questions/43055706/… 和此:stackoverflow.com/questions/34734671/… 以了解异步性。 -
@dskrvk 感谢您告诉我。我已经去掉了不必要的东西。
-
@AJT_82 我做了一些修改。请通过同样的方式。
-
@AJT_82 是正确的,这是异步的问题。渲染 dom 时,
q尚未定义。
标签: html json angular typescript data-binding