首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何管理请求循环中的数据

如何管理请求循环中的数据
EN

Stack Overflow用户
提问于 2021-11-28 02:18:33
回答 3查看 71关注 0票数 0

我使用的是WooCommerce v3 api,我的目标是显示一个包含所有类别的列表,并按类别水平显示所有产品,例如:

类别名称:

产品product1 product2

类别2名称:

产品product1 product2

但是没有端点来获取所有这些,所以我首先从

代码语言:javascript
复制
  getAllCats(): Observable<any>{
    const req = this.httpS.get(`${API.prod.url+API.prod.woo+'products/categories/?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret}`);
    return req;
  }

  getProductsByCat(catId: number): Observable<any>{
    const req = this.httpS.get(`${API.prod.url+API.prod.woo+'products?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret+'&category='+catId}`);
    return req;
  }

然后在我的部分中,我要这样做

代码语言:javascript
复制
categories: any = {};
  cats: Array<any> = [];
  products: Array<any> = [];
  catsWithAllProducts: any = {
    category: [{
      products: []
    }]
  };
  kats: Category[] = [];



showAllCatsWithProducts(){
    this.pService.getAllCats().subscribe((cats) => {
      for (const [i,cat] of cats.entries()) {
        this.pService.getProductsByCat(cat.id).subscribe((products) => {
          this.cats.push(cat);
          this.products.push(products);
          this.catsWithAllProducts.category = cat;
          this.kats.push(this.catsWithAllProducts); //new categories array with products
        });
      }
    });
  }

我有两个问题,products[]是空的,我很困惑,如何实现创建一个新的对象或数组或一个类别中的所有产品的对象数组。对,屏幕上打印的是所有类别,但有重复的名称:

我有10个类别,它显示了接收*类别数的第一个名称。我一直在想的是,首先,它应该是异步的,我的意思是,它是一个可观察的,但它正在推到数组,每个元素是否有响应。我被困在这里了,谢谢你读我的书。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-11-28 20:22:10

我使用异步/等待处理它,并将常规的forshowAllCatsWithProducts()方法中更改为forEach

代码语言:javascript
复制
  async showAllCatsWithProducts(){
    this.pService.getAllCats().subscribe((cats) => {
      cats.forEach(async cat => { //for each category
        const response = await this.pService.getProductsByCat(cat.id).subscribe(res => { //It's gonna wait por their products
          this.categories.push({id: cat.id,name: cat.name,slug:cat.slug, products: res}); //Push category with products
        });
      });
    });
  }
票数 0
EN

Stack Overflow用户

发布于 2021-11-28 03:13:15

我不太确定,但请尝试一下,如果在代码中更改了这些内容,则可以解决可能出现的异步问题:

代码语言:javascript
复制
getAllCats(): Observable<any>{
   return this.httpS.get(`${API.prod.url+API.prod.woo+'products/categories/?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret}`);
}
getProductsByCat(catId: number): Observable<any>{
   return this.httpS.get(`${API.prod.url+API.prod.woo+'products?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret+'&category='+catId}`);
}


showAllCatsWithProducts() {
    this.pService.getAllCats()
    .pipe(
       switchMap( cat => this.pService.getProductsByCat(cat.id) ),
    )
    .subscribe( products => {
       this.cats.push(cat);
       this.products.push(products);
       this.catsWithAllProducts.category = cat;
       this.kats.push(this.catsWithAllProducts);
     });
)
票数 0
EN

Stack Overflow用户

发布于 2021-11-28 18:58:01

我建议首先更改服务,将所需的内容定义为可观察的,尽可能地对组件隐藏复杂性,如下所示:

代码语言:javascript
复制
export interface Category {
  id: number;
}

export interface Product {
  id: number;
}

@Injectible()
export class pService {
  readonly categories$: Observable<Category[]> = this.httpS.get(`${API.prod.url+API.prod.woo+'products/categories/?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret}`).pipe(
    take(1),
    shareReplay()
  );
  
  readonly productsPerCategory$: Observable<[Category, Product[]]> = this.categories$.pipe(
    mergeMap(category => this.getProductsByCat(category.id).pipe(
      map(products => [category, products])
    )),
    shareReplay()
  );
  
  readonly allProducts$: Observable<Product[]> = this.productsPerCategory$.pipe(
    mergeMap(ppc => from(ppc[1])),
    distinct((p: Product) => p.id), // if products overlap, otherwise remove this line if every product is in only one category.
    shareReplay()
  );
  
  readonly allProducts: Promise<Product []> = this.allProducts$.pipe(toArray()).toPromise;
  
  private getProductsByCat(catId: number): Observable<Product[]>{
    return this.httpS.get(`${API.prod.url+API.prod.woo+'products?consumer_key='+API.prod.consumer_key+'&consumer_secret='+API.prod.consumer_secret+'&category='+catId}`);
  }
}

这都是没有订阅的。如果您使用异步管道(取决于您需要什么),那么您也可以在评论中没有一个订阅就可以离开。

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

https://stackoverflow.com/questions/70140171

复制
相关文章

相似问题

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