I have a subject defined as below
this.checkListSubject
.pipe(
takeUntil(this._unSubscribeAll),
filter((filter) => !!filter),
switchMap((index) => this._api.get('getMyData')),
tap((list) => this.gateEditArrayModal.toArray()[index].display(list))
)
.subscribe();
As I understand the tap cannot have the value of index because its lost after switchMap. There is any way to get the value of index in tap?
Thanks
CodePudding user response:
Yes, but you need to use a nested pipe. In the pipe you map the result into the original index together with the result
switchMap(index => this._api.get( 'getMyData' ).pipe(
map(result => ({result, index}))
)),
// use the index
tap(({index}) => this.gateEditArrayModal.toArray()[index].display()),
// back to the result
map(({result}) => result),
CodePudding user response:
You can achieve that in different ways using other RxJS operators, such as map or withLatestFrom.
- Using the
withLatestFrom
operator instead ofswitchMap
:
this.checkListSubject
.pipe(
takeUntil(this._unSubscribeAll),
filter((filter) => !!filter),
withLatestFrom(this._api.get('getMyData')),
tap(([index, list]) =>
this.gateEditArrayModal.toArray()[index].display(list)
)
)
.subscribe();
- Using the
map
operator withswitchMap
:
this.checkListSubject
.pipe(
takeUntil(this._unSubscribeAll),
filter((filter) => !!filter),
switchMap((index) =>
this._api.get('getMyData').pipe(map((list) => [index, list]))
),
tap(([index, list]) =>
this.gateEditArrayModal.toArray()[index].display(list)
)
)
.subscribe();