Wiggy A.
Wiggy A.

Reputation: 496

Combine requests in series - Angular 7

I'm trying to chain a few requests in a series, something like forkJoin but the requests NOT being requested in parallel. Here's what I have so far:

let nodeDetails = this.http.get('node/1/')
let nodeParents = this.http.get('nodeParents/1/')
let nodeTree = this.http.get('nodeTree/1/')
let nodeUsers = this.http.get('nodeUsers/1/')
let nodeDocuments = this.http.get('nodeDocuments/1/')
var requests = [nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments]
forkJoin(requests)
  .subscribe(responses => {
    // List of all responses from all of the requests
    console.log(responses)
  })

I read somewhere that concat can be used in combination with toArray, but that was apparently taken out in recent rxjs updates. Is there any way to do this currently?

EDIT - The final goal is something similar to this answer. The code in that answer is no longer working in Angular 7 and Rxjs 6.2.2.

Upvotes: 0

Views: 116

Answers (2)

Wiggy A.
Wiggy A.

Reputation: 496

Here's what ended up working:

import { toArray } from 'rxjs/operators';
import { concat } from 'rxjs';

let nodeDetails = this.http.get('node/1/')
let nodeParents = this.http.get('nodeParents/1/')
let nodeTree = this.http.get('nodeTree/1/')
let nodeUsers = this.http.get('nodeUsers/1/')
let nodeDocuments = this.http.get('nodeDocuments/1/')
const requests = concat(nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments)

requests
    .pipe(toArray())
    .subscribe(responses => {
        // Array of responses
    })

The toArray() operator waits for all responses - in the order provided in concat.

Upvotes: 2

veben
veben

Reputation: 22262

You can use concat from Rxj6. Tyry something like that:

//  RxJS v6+
import {concat} from 'rxjs';

let nodeDetails = this.http.get('node/1/')
let nodeParents = this.http.get('nodeParents/1/')
let nodeTree = this.http.get('nodeTree/1/')
let nodeUsers = this.http.get('nodeUsers/1/')
let nodeDocuments = this.http.get('nodeDocuments/1/')

const requests = concat(nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments)

The use forkjoin for parallel or Rxjs operator, like concatMap for non-parallel

Upvotes: 1

Related Questions