简体   繁体   中英

Waiting for first call (subscription) in ngOnInit()

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM