0
votes

I am trying to get a member value from other web api in rxjs.

I did this in a pipe method with switchMap. But if there is a problem with getting the member value then I want to skip old model with values to next method.

So I dont want to return null after switchMap worked.

Here is my code:

    (this.repository.getData(`employeecards/list/${this.currentUser.companyId}`) as Observable<EmployeeCard[]>)
    .pipe(
      flatMap(emp => emp),
      tap(emp => emp),
      switchMap((empCard: EmployeeCard) => this.repository.getData(`cards/${empCard.cardId}`),(empCard, card) => ({ empCard, card }) ),
//second subscribe
      switchMap((emp: { empCard: EmployeeCard, card: LogisticCard }) => this.parraApiService.getBalanceByBarcode(emp.card.barcode),
        (emp: { empCard: EmployeeCard, card: LogisticCard }, apiRes: ParraApiResult) => {
          if (apiRes.response.isSuccess) {
//I use this subscribe only set to balance
            emp.empCard.balance = apiRes.response.data['balance'];
          }
          return emp.empCard
        }),
      catchError((e) => {
        return of([]); //I want to retun emp value 
      }),
      reduce((acc, value) => acc.concat(value), [])
    )

How can I solve this problem?

Thanks

1
Return EMPTY instead of of([]) - martin
Its not empty its old value. EmployeeCard model value that I want to get - tcetin

1 Answers

0
votes

I think you can achieve that by creating a closure:

(this.repository.getData(`employeecards/list/${this.currentUser.companyId}`) as Observable<EmployeeCard[]>)
  .pipe(
    flatMap(emp => emp),
    tap(emp => emp),
    switchMap((empCard: EmployeeCard) => this.repository.getData(`cards/${empCard.cardId}`), (empCard, card) => ({ empCard, card })),
    switchMap(
      (emp: { empCard: EmployeeCard, card: LogisticCard }) => this.parraApiService.getBalanceByBarcode(emp.card.barcode)
        .pipe(
          map((emp: { empCard: EmployeeCard, card: LogisticCard }, apiRes: ParraApiResult) => {
            if (apiRes.response.isSuccess) {
              emp.empCard.balance = apiRes.response.data['balance'];
            }
            return emp.empCard
          }),
          catchError((e) => {
            // `emp` available because of closure
            return of(emp);
          }),
        )
    ),
    reduce((acc, value) => acc.concat(value), [])
  )

Also notice that I gave up on switchMap's custom resultSelector, as it can easily be replaced with a map operator.