如何在promise中简化这个有角度的重复代码?

问题描述 投票:0回答:2

我是一名新的Angular开发人员。我想知道是否有一种优雅的方法来简化下面的重复代码。

addTransaccion() {
    try {
      if (this.idTransaccion === '0') {
        this.transaccionesSrv.addTransaccion(data)
          .then(res => {
            if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
            }
          });
      } else {
        this.transaccionesSrv.actualizarTransaccion(data, this.idTransaccion)
          .then(res => {
            if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
            }
          });
      }
    } catch (error) {
      this.envioFormularioOk = false;
    }
  }
angular typescript
2个回答
0
投票

也许这样的事情

 (this.idTransaccion === '0' ? this.transaccionesSrv.addTransaccion(data) : 
this.transaccionesSrv.actualizarTransaccion(data, this.idTransaccion))
          .then(res => {
            if (res) {
              this.router.navigate(['/cuentas/transacciones'], { queryParamsHandling: "preserve" });
            }
          });

但我认为阅读起来比较困难


0
投票
const manageTransaction = (data)=>{
 if (this.idTransaccion === '0')
    return transaccionesSrv.addTransaccion(data);
  else
    return this.transaccionesSrv.actualizarTransaccion(data,
                                                       this.idTransaccion);
};
const navigate = (res) => {
 if (res) {
    this.router.navigate(['/cuentas/transacciones'], { 
       queryParamsHandling: "preserve" });
   }
};


const addTransaccion = () => {
  manageTransaccion(data)
  .then(res => navigate(res););
  .catch((error)=> {
    this.envioFormularioOk = false;
  });} 
© www.soinside.com 2019 - 2024. All rights reserved.