Search code examples
angularrxjsreactive

Angular RxJS Streams HTTP Request - Show more items - Part 2


Regarding my request about how to implement the show more functionality with SCAN (Angular RxJS Streams HTTP Request - Show more items). How can I merge the response (scan) only when the offset has been updated not when search paramMap is updated ?

My Service that returns the data

public getProductsV3(paramMap: Observable<ParamMap>):Observable<ProductResponseApi>{


const combineLatest$ = combineLatest([this.offset$,this.limit$,paramMap]).pipe(
  switchMap(([offset,limit,paramMap])=>this.fetchProductsFromApiV2(offset,limit,paramMap.get('q') as string))
)

return combineLatest$.pipe(
  scan((prev, current) => {
    return {
      infos: current.infos,
      products: [...prev.products, ...current.products]
    };
  })
);
}

It works, however when I look for another product using the ParamMap it's combined with the previous result because of the scan. How can I scan only when the offset has changed ?


Solution

  • I found a response from my question. Thanks to this video https://www.youtube.com/watch?v=aKsPMTP6-sY&t=970s&ab_channel=JoshuaMorony

    return combineLatest([paramMap]).pipe(
      switchMap(([search])=> {
        const productForCurrentPage$ = this.offset$.pipe(
          concatMap((offset) =>
            this.http.get<ProductResponseApi>(this.apiUrl+`/search?q=${search.get('q')}&offset=${offset}`)
          )
        )
    
        const allProducts$ = productForCurrentPage$.pipe(
          scan((prev, current) => {
            return {
              infos: current.infos,
              products: [...prev.products, ...current.products]
            };
          })
        )
    
        return allProducts$;
      })
    )