Angular rxjs conditionally call HTTP endpoint

408 Views Asked by At

I'm trying to do some Trello automation so I'm making an API call to create a list, which returns an ID. Then, if I specified card names, I need to make another set of calls in parallel using the list ID. Whether or not I create cards, I want to return the ID of the list which was created.

The compiler doesn't like what I did on the iif call though, saying this:

TS2345: Argument of type 'Observable<string[]>' is not assignable to parameter of type '(value: HasId, index: number) => ObservableInput'.   Type 'Observable<string[]>' provides no match for the signature '(value: HasId, index: number): ObservableInput'.

I'm not sure exactly why it wants to assign to (value: HasId, index: number) => ObservableInput<any> though, so I don't know how to fix.

This was the code that I tried to use.

interface HasId {
    id: string
}

private createCard(idList: string, name: string): Observable<string> { ... }

private createList(boardId: string, name: string, cards?: string[]): Observable<string> {
  let idList = ''

  return this.http.post<HasId>(`boards/${boardId}/lists`, null, {params: {name}})
    .pipe(
      tap(x => idList = x.id),
      mergeMap(
        iif(
          () => cards,
          forkJoin(cards.map(name => this.createCard(idList, name)))
      )),
      map(() => idList)
    )
}
2

There are 2 best solutions below

0
On BEST ANSWER

You have to return a value from mergeMap's projection function:

mergeMap(() => 
  iif(
    () => cards,
    forkJoin(cards.map(name => this.createCard(idList, name)))
  )
),
0
On

Looking at your error you'll be able to notice that mergeMap accepts a function returning an Observable (rather than an actual Observable), therefore consider modifying your code as below:

mergeMap(() =>
  iif(     
    () => cards,
    forkJoin(cards.map(name => this.createCard(idList, name)))
  )
)