0

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 ?

mbagiella
  • 256
  • 2
  • 12

2 Answers2

0

Try withLatestFrom

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

or take

const combineLatest$ = combineLatest([this.offset$,this.limit$,paramMap.pipe(take(1))]).pipe(
  switchMap(([offset,limit,paramMap])=>this.fetchProductsFromApiV2(offset,limit,paramMap.get('q') as string))
)
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • It doesn't work, I tried both and the fetchProduct doesn't trigger when param change – mbagiella Dec 07 '22 at 10:57
  • " Expected behaviour : When a new params is emmited the scan shouldn't be triggered" I thought that is what you wanted? – MoxxiManagarm Dec 07 '22 at 10:59
  • The scan (merging current and previous result together) but it should at least trigger the fetchProductFromApi – mbagiella Dec 07 '22 at 11:01
  • I'm not explaining correctly. When user search a new product then it should return a new observable object and in the front the user can show more items but when he enter a new query in the search then the scan should not be in use. – mbagiella Dec 14 '22 at 12:29
0

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$;
  })
)
mbagiella
  • 256
  • 2
  • 12