Reputation: 123
I'm working on a feature of a commerce using sap spartacus-storefront.
I'm trying to implement a custom GTM event on a products carousel component.
Actually, my code have the lines below who gets the Observable of product items:
items$: Observable<Observable<CustomProduct>[]> = this.componentData$.pipe(
map(data => data.productCodes?.trim().split(' ') ?? []),
map(codes => codes.map(code => this.productService.get(code, this.PRODUCT_SCOPE)))
);
If i use a rxjs's tap, I got something like this:
items$: Observable<Observable<CustomProduct>[]> = this.componentData$.pipe(
map(data => data.productCodes?.trim().split(' ') ?? []),
map(codes => codes.map(code => this.productService.get(code, this.PRODUCT_SCOPE))),
tap(products => console.log(products)) // [Observable<CustomProduct>, Observable<CustomProduct>, Observable<CustomProduct>...]
);
If a try to map or make a foreach on products var, all my resuts are [undefined, undefined, undefined...]
Have another way to catch this array of products?
Upvotes: 1
Views: 133
Reputation: 3521
items$: Observable<CustomProduct[]> = this.componentData$.pipe(
map(data => data.productCodes?.trim().split(' ') ?? []),
switchMap(codes => forkJoin(
codes.map(code => this.productService.get(code, this.PRODUCT_SCOPE))
))
);
Map is for replacing values inside a stream, what you want is replacing a stream, so use switchMap
.
forkJoin is the equivalent of Promise.all
.
And finally, use the correct typing on your final observable. You can also infer it directly from your service call, if you have provided a type to your service function.
Upvotes: 3