首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular optimize api

Angular optimize api
EN

Stack Overflow用户
提问于 2019-02-03 23:29:07
回答 1查看 34关注 0票数 0

我试着用angular做一个"BBoard“。

代码语言:javascript
复制
<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>

我的函数是:

代码语言:javascript
复制
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的变量。但我不知道该怎么做。

我将主题和类别分开:

代码语言:javascript
复制
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制作的)

EN

回答 1

Stack Overflow用户

发布于 2019-02-03 23:50:30

您可以使用forkJoin同时运行两个请求。这样,您将同时获得两个请求的响应,并且可以对它们执行任何操作。

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54504428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档