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

时间:2019-10-01 15:07:23

标签: angular

在开始第二个请求之前,我需要等待第一个电话。我是JS的新手,所以我认为这很简单。我读过有关异步/等待的内容,但在这个示例中我不知道如何实现

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

1 个答案:

答案 0 :(得分:0)

您必须使用switchMap() rxjs运算符,该运算符可帮助您获得第一个响应,然后定位第二个请求。您也可以取消不需要的请求。

以下代码分为许多部分,易于理解。如果愿意,可以将所有内容组合在一起。

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

为简便起见,您可以使用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()