infodev
infodev

Reputation: 5235

chaining two observables in angular

save(body) {
  let headers = new HttpHeaders()
  headers.append('Content-Type', 'text/plain')
  return this.callWorkflowService
    .getRawDataflow()
    .pipe(
      map(data => {
        data['jobs'] = body
        return data
      })
    )
    .pipe(newData => // correspond to `return data` 
      this.httpClient
        .post(this.url, JSON.stringify(newData), { headers: headers })
        .pipe(
          map(res => {
            return res
          })
        )
    )
}

What I'm getting actually inside the httpRequest is an Observable instead of an Object. I don't understand why.

Upvotes: 0

Views: 722

Answers (2)

Siddharth Pal
Siddharth Pal

Reputation: 1458

Here when you are chaining multiple Observables you are creating a Observable of Observables. So you need to flatten them before you chain them. RxJS provides multiple flattening operators like switchMap , mergeMap, concatMap and exhaustMap for flattening Observables.

  save(body) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'text/plain');
    return this.callWorkflowService.getRawDataflow().pipe(
      map(data => ({data, ...{"jobs": body}})),
      mergeMap(newData =>
        this.httpClient.post(this.url, JSON.stringify(newData), {
          headers: headers
        })
      )
    );
  }

This is a wonderful article which talks about flattening of Observables.

Upvotes: 2

Andrei
Andrei

Reputation: 12206

you should use switch map operator for example

 return this.callWorkflowService
    .getRawDataflow()
    .pipe(
      map(data => {
        data['jobs'] = body
        return data
      }),
    switchMap(() => this.httpClient
        .post(this.url, JSON.stringify(newData), { headers: headers })
        .pipe(
          map(res => {
            return res
          })
        ))
    )

Upvotes: 1

Related Questions