我已经写了下面的代码和类别不显示在html模板。但是,当我删除getSubject()并将其代码放入getSubjects()方法中时,一切都正常工作。为什么我不能把这两个方法分开?
export class SubjectComponent implements OnInit {
subject: Subject;
subjects = [];
constructor(private subjectService: SubjectService) { }
ngOnInit() {
this.getSubjects();
this.getSubject();
}
getSubjects(){
this.subjectService.getSubjects().subscribe(result => {
this.subjects = result;
});
}
getSubject(){
this.subjects.forEach((s: Subject) => {
if (s.name.toLowerCase() === 'math'){
this.subject = s;
}
});
}
Html模板:
{{subject?.name}}
<ol>
<li *ngFor="let category of subject?.categories">
<p>{{category?.name}}</p>
</li>
</ol>
为什么要分别调用它们呢?基本上,当你调用你的服务时,它会去获取数据。当数据返回时(在某个时间点),执行subscribe
代码。当数据返回时,你会想要遍历它并设置主题。如您所见,调用getSubject()
将很有可能尝试遍历空数组,因为数据尚未返回。
export class SubjectComponent implements OnInit {
subject: Subject;
subjects: Subject[] = [];
constructor(private subjectService: SubjectService) { }
ngOnInit() {
this.subjectService.getSubjects().subscribe(result => {
this.subjects = result;
this.subjects.forEach((s: Subject) => {
if (s.name.toLowerCase() === 'math'){
this.subject = s;
}
});
});
}