我试着用angular做一个"BBoard“。
<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;
}问题是这确实引入了循环,并且没有被推荐,所以我必须使用已经包含category + 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时,我可以在循环中运行REQUEST,但使用angular时,逻辑会发生变化,这并没有得到优化。你会怎么做?( API是用PHP vanilla制作的)
发布于 2019-02-03 23:50:30
您可以使用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);
});
}另外,我建议在topics中使用filter而不是forEach。有关更多信息,请参阅this
https://stackoverflow.com/questions/54504428
复制相似问题