0

I need to wait for first call, before start second request. I'm new in js so I think that it could be simple. I was read smth about async/await but i don't have idea how to implement it in this example

ngOnInit() {
  this.firstService.get$(this.orderNumber).subscribe(
      first => this.firstModel = first,
      e => {
        for (const error of e.errors) {
          this.messages.push({
            _type: MessageType.ERROR,
            code: error.messageCode
          });
        }
      }
  );
  this.secondService.getReasons$(this.firstModel).subscribe(
      second => this.secondModel = second,
      e => {
        for (const error of e.errors) {
          this.messages.push({
            _type: MessageType.ERROR,
            code: error.messageCode
          });
        }
      }
  );
}

this.firstModel is undefined in second step.

ore ore
  • 79
  • 1
  • 2
  • 6
  • Possible duplicate of [Angular - Make multiple HTTP calls sequentially](https://stackoverflow.com/questions/51212448/angular-make-multiple-http-calls-sequentially) – mbojko Oct 01 '19 at 15:17

1 Answers1

1

You have to use switchMap() rxjs operator which helps you to get the first response then target the second request. And you can cancel the request if you don't need.

The below codes are divided into many parts to be understood easily. If you like, you can combine all.

    // Define both requests
    const firstReq = this.firstService.get$(this.orderNumber)
    const secondReq = this.secondService.getReasons$(this.firstModel);

    // combined has both response
    const combined= firstReq.pipe(switchMap(firstData =>{
        return secondReq ;
    }))

    combined.subscribe()

For the easiness, you can use tap operator to check both response

const combined= firstReq.pipe(switchMap(firstData =>{
        return secondReq.pipe(tap(secondData =>{
            console.log('First request data',firstData);
            console.log('Second request data',secondData);
        }))
    }))

combined.subscribe()
varman
  • 8,704
  • 5
  • 19
  • 53