簡體   English   中英

Angular Rxjs 如何使用行為主題進行分頁

[英]Angular Rxjs How to paginate using Behavior Subject

我正在使用類別 ID 為產品列表構建過濾器,並使用 RXJS 操作符BehaviorSubject執行此操作。

我的問題是我無法無限滾動 Behavior Subject,因為我無法獲取先前的數據數組( products ),因為顯然總是獲取我更新的最新數據。

我的服務:

private productsSource = new BehaviorSubject<Product[]>(null);
public products$: Observable<Product[]> = this.productsSource.asObservable();
async getProductsByCategory(category: string, page: string = '1'): Promise<void> {
  const products = await this.http.get<Product[]>(`${environment.host + this.wooPath}products`, {
    params: {
      ...environment.configtations,
      category,
      page,
      lang: this.language,
      per_page: '6',
      not_tags: 'component'
    }
  })
    .toPromise();

  this.productsSource.next(products);
}

我的加載更多(分頁):

async loadData(event) {
 // what next?
}

更改this.productsSource.next(products); 到:

this.products.next({
   previous: this.products.value.current
   current: products
});

和定義:

private productsSource = new BehaviorSubject<any>(null);
// You could also make a type for that like:
// { previous: Product[], current: Product[] }

然后你總是有前一個和當前的。

如果您想實現無限滾動,我建議您將所有值更改為專用數組,例如:

products$.subscribe((value) => {
   this.someProductsArray = [...this.someProductsArray, ...value];
});

我找到了一種完美適合我的情況的方法,

它的代碼:

我的服務:只是從getProductsByCategory方法返回一個產品列表作為承諾:

/**
 * @name getProductsByCategory
 * @param category 
 * @param page 
 */
async getProductsByCategory(category: string, page: string = '1'): Promise<Product[]> {

  // getting products
  const products = await this.http.get<Product[]>(`${environment.host + this.wooPath}products`, {
    params: {
      ...environment.configtations,
      category,
      page,
      lang: this.language,
      // per_page: '6',
      not_tags: 'component'
    }
  })
    .toPromise();

  return products;
}

然后創建一個返回productsSource的新方法:

filteringProduct() {
  return this.productSource;
}

在組件上:在ngOnInit給它一個初始值:

async ngOnInit() {
  // get the category id
  const id = this.route.snapshot.paramMap.get('id');
  this.categoriesIds = id;

  // get gategory and its sub categories Or Prodicts by category id
  [this.category, this.subCatergories] = await Promise.all([
    this.wooService.getCategoryById(id),
    this.wooService.getSubCategories(id)]);

  // setting products
  this.wooService
    .filteringProduct()
    .next(
      await this.wooService.getProductsByCategory(this.categoriesIds)
    );

  this.wooService.products$
  .pipe(
    takeUntil(this.unsubscribe)
  )
  .subscribe(data => this.products = data);

}

我的loadMore

async loadData(event) {

  // next page number
  this.currentPage++;

  // const id = this.category.id.toString();

  // next page content
  const nextPage = await this.wooService.getProductsByCategory(
    this.categoriesIds,
    this.currentPage.toString()
  );

  // concat all together
  this.products = this.products.concat(nextPage);

  // compelete the loading
  event.target.complete();

  // checking if all data loaded from the server
  if (nextPage.length === 0) {
    this.infinite = false;
  }

}

您可以使用count()運算符來存儲頁碼,只需一個普通主題即可完成這項工作。

currentPage=Subject();
getProduct=(page)=>
this.http.get<Product[]>(`${environment.host + this.wooPath}products`, {
    params: {
      ...environment.configtations,
      category,
      page,
      lang: this.language,
      per_page: '6',
      not_tags: 'component'
    }
  })


data=loadMore.pipe(
  count(),
  mergeMap(page=>getProduct(page)),
     scan((acc,curr)=>{
         return acc.concat(cur.res)
     },[])
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM