简体   繁体   English

在 ngOnInit() 中等待第一次调用(订阅)

[英]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.我是 js 新手,所以我认为它可能很简单。 I was read smth about async/await but i don't have idea how to implement it in this example我读过关于 async/await 的消息,但我不知道如何在这个例子中实现它

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. this.firstModel在第二步中未定义。

You have to use switchMap() rxjs operator which helps you to get the first response then target the second request.您必须使用switchMap() rxjs 运算符,它可以帮助您获得第一个响应,然后定位第二个请求。 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为方便起见,您可以使用tap运算符来检查两个响应

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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