角度优化API

时间:2019-02-03 15:29:07

标签: angular api

我试图用角形制作一个“ 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;
}

问题在于这确实存在infite循环,并且不建议这样做,因此我必须使用已经包含category + topic的变量。但是我不知道该怎么办。

我将主题和类别分开:

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,但是使用角度进行逻辑更改,而这根本没有优化。你会怎么做? (API是用PHP香​​草制作的)

1 个答案:

答案 0 :(得分:0)

您可以使用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的{​​{1}}。有关更多信息,请参见this

相关问题