在ngoninit()方法中的两个订阅之间切换



我有一个页面,我将发票填充到网格中。在网格中,可以选择查看特定发票的付款。该按钮将用户从发票页面切换到付款页面,然后过滤所有付款,以便仅显示与该特定发票相对应的付款。另外,当单击付款页面本身时,它将所有付款填为网格。我在ngoninit((方法中都完成了这两种事情,但是,我需要能够在两者之间切换。换句话说,当用户单击发票页面上的按钮时,我想过滤付款,当用户单击"纳维尔"中的付款选项卡时,我希望它显示所有付款。因此,我已经测试了两个订阅并知道它们有效,但是如何在两个订阅之间切换以实现这一目标?任何帮助都将不胜感激。

我在IF语句中使用了不同的变量和平等检查,甚至尝试更改IF语句的行位置,但没有Prevail

ngOnInit() {
  this.sub = this.route.params.subscribe(
    params => {
      if (params == null) { //HERE LIES THE ISSUE
         this.invoiceNum = params['invoiceNum'];
         //displays FILTERED payments
        this.paymentService.showPayments(this.invoiceNum).subscribe(
        res => {
          this.payments = res.value;
          this.loading = false;
          console.log(res);
        },  
        err => {
          if (err.status == 401) {
            this.auth.logOut();
          }
          this.loading = false;
          console.log(err);
        }
      );
    } else {
      //displays ALL payments
      this.paymentService.getPayments().subscribe(
        res => {
          this.payments = res.value;
          this.loading = false;
          console.log(res);
        },
        err => {
          if (err.status == 401) {
            this.auth.logOut();
          }
          this.loading = false;
          console.log(err);
        }
      );
    }
   }
 );
}

您可以使用switchMapswitchMap可以为条件返回不同的主题。

此解决方案切换Route Parameter ChangesHTTP Request for payments主题的约束。如果路由器参数包含invoiceNum,它将返回invoiceNum的特定付款主题。或者,它将返回所有付款的主题。

您可以在两种情况下重复使用ONENT/ONERROR回调。

ngOnInit() {
  this.sub = this.route.params
  .pipe(
    switchMap(params => {
      if (params['invoiceNum'] !== undefined) {
        //displays FILTERED payments
        return this.paymentService.showPayments(this.invoiceNum);
      } else {
        //displays ALL payments
        this.paymentService.getPayments();
      }
    })
  )
  // Reuse onNext/onError callbacks
  .subscribe(
    res => {
      this.payments = res.value;
      this.loading = false;
      console.log(res);
    },  
    err => {
      if (err.status == 401) {
        this.auth.logOut();
      }
      this.loading = false;
      console.log(err);
    }
  );
}

最新更新