我试图做一个“局”有棱有角。
<div *ngFor="let category of categories">
{{ category.name }}
<div><a pageScroll href="home#add">Nouveau sujet</a></div>
<div *ngIf="hasTopics(category.id)">
has topic
<div *ngFor="let topic of getTopicsOf(category.id)">
{{ topic.title }}
</div>
</div>
</div>
而我的功能:
getTopicsOf(id: number) {
const topics = [];
this.topics.forEach(element => {
if (element[0].category_id === id) {
topics.push(element[0]);
}
});
console.log(topics);
return topics;
}
问题是这样做无限循环,它不是推荐,所以我必须使用已经包含类别+主题变量。但我不知道该怎么办。
我得到的主题和类别分开:
getAll() {
this.topicsService.getAll().subscribe((res) => {
this.count = res.count;
if (res.count > 0) {
this.topics.push(res.topics);
}
});
}
getCategories() {
this.topicsService.getAllCategories().subscribe((res) => {
if (res.count > 0) {
res.categories.forEach((cat) => {
this.categories.push(cat);
});
}
});
}
我必须在同一个要求吗?
当我使用HTML + PHP我可以在里面循环,但具有角的逻辑变化运行请求并且这不是在所有优化。你会怎么做? (API被用PHP香草制造)
您可以使用forkJoin
同时运行两个请求。这样,您将有两个请求在同一时间的响应,并可以与他们做任何事。
import { forkJoin } from 'rxjs';
getAll() {
forkJoin(this.topicsService.getAll(), this.topicsService.getAllCategories()).subscribe(data => {
const { topicsRes, categoriesRes } = data;
if (res.count > 0)
this.count = topicsRes.count;
if (categoriesRes.count > 0)
this.categories = categoriesRes.categories;
this.topics = [];
topicsRes.topics.forEach(element => {
if (element[0].category_id === id) {
this.topics.push(element[0]);
}
});
console.log(this.topics);
});
}
此外,我建议使用filter
的而不是forEach
为topics
。见this更多信息