角度优化 api

  • 本文关键字:api 优化 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;
}

问题是这确实是循环并且没有被重新推荐,所以我必须使用已经包含类别 + 主题的变量。但我不知道该怎么做。

我将主题和类别分开:

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 原版制作的)

您可以使用

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。有关更多信息,请参阅此处

最新更新