0

I'm trying to implement the show more button functionality, when you press it should call the api with the next offset and merge the value with the previous result. From what I saw so far I should use the SCAN function, however I'm lost.

When I click show more the offset is updated

public showMore(offset:number){
  this.offset$.next(offset)
}

The api is returning this object

{
 requestInfo:Info,
 product:Product[]
}

Info contains the number of results and the next offset, product contains a list of product (product name, price etc...)

What I tried so far is

public getProductsV3():Observable<ProductResponseApi>{

const combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

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

But obviously it doesn't work

public getProductsV2():Observable<ProductResponseApi>{

return combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

}

The version 2 is working, however it shows the next pages without keeping the old values.

The fetchProduct is quite simple

private fetchProductsFromApiV2(currentOffset:number,limit:number){ 

const params = new HttpParams().set('offset', currentOffset).set('limit', limit);
return this.http.get<ProductResponseApi>(this.apiUrl+'/products',{params,withCredentials:true});
}

Thanks for help

mbagiella
  • 256
  • 2
  • 12
  • 1
    your function inside `scan` is not returning anything. To use implicit return with an object, you need to wrap with parenthesis: `scan((prev,current)=> ({infos:current.infos,products:[...prev.product,...current.products]}))` – BizzyBob Dec 06 '22 at 15:12
  • I'm voting to close as typo, your mistake is basically forgetting parentheses around the object you want to return, as BizzyBob mentioned. See also [ECMAScript 6 arrow function that returns an object](https://stackoverflow.com/questions/28770415/ecmascript-6-arrow-function-that-returns-an-object) – Lukas-T Dec 06 '22 at 18:05

0 Answers0