首页 > 解决方案 > 在 ngOnInit() 中等待第一次调用(订阅)

问题描述

我需要等待第一个电话,然后再开始第二个请求。我是 js 新手,所以我认为它可能很简单。我读过关于 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在第二步中未定义。

标签: angular

解决方案


您必须使用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()

推荐阅读