Search code examples
rxjsrxjs6

Angular rxjs conditionally call HTTP endpoint


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)
    )
}

Solution

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

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