在Angular中使用if条件等待可观察到的响应

时间:2018-12-26 13:40:36

标签: angular observable

我正面临Observable问题。编写问题陈述。

我正在从客户那里收到一个带有PO号的订单,但有时客户订单缺少PO号,所以我只创建临时PO号并将其填写在表格中并接收订单。但是,当我致电临时PO号码创建服务时,它不会等待响应。检查下面的代码。

  

如果条件匹配且仅填写表格数据,则仅调用this._partReceivingService.generateTempPo()服务,否则用户将填写客户的订单

if (this.partRecevingForm.controls.ShipperHasNoPO.value == true) {
       this._partReceivingService.generateTempPo().subscribe(res=>{
          this.partRecevingForm.controls.customerOrderNumber.setValue(res.tempPONo);
      })
  }
//then i am executing receiving order service
this._partReceivingService.receiveNewPart(this.partRecevingForm.value).subscribe(data=>{
   //notifications
})

3 个答案:

答案 0 :(得分:0)

我认为您可以尝试以下方法:

canvasView.subviews.forEach {
    switch $0 {
    case is CircleView:
        $0.backgroundColor = /* UIColor */
    case is SquareView:
        $0.backgroundColor = /* UIColor */
    ...
    default:
        continue
    }
}

答案 1 :(得分:0)

可观察对象异步工作。当您调用它们时,您的代码中有一部分将等待完成,但是其余代码将继续运行。例如此功能

myFunc() {
    console.log('hello 1');
    this.myservice.getSomething().subscribe(() => console.log('hello 2'));
    console.log('hello 3');
}

将在控制台中生成

> hello 1
> hello 3
> hello 2

因此,您必须将第二个服务呼叫放在第一个服务呼叫的subscribe内。另外,我建议使用patchValue()代替controls.fieldName.setValue()

if (this.partRecevingForm.controls.ShipperHasNoPO.value == true) {
       this._partReceivingService.generateTempPo().subscribe(res=>{
          this.partRecevingForm.patchValue({customerOrderNumber: res.tempPONo});

          this._partReceivingService.receiveNewPart(this.partRecevingForm.value).subscribe(data=>{
             //notifications
          });
      });
} else {
    this._partReceivingService.receiveNewPart(this.partRecevingForm.value).subscribe(data=>{
      //notifications
    })
 } 

答案 2 :(得分:0)

我不能发表评论,因为我是新来的,但rhavelka是正确的,如果您不想两次编写相同的代码,只需将其放入方法中即可。