首页 > 解决方案 > 如果 API 调用失败,如何将切换状态更改为原始状态

问题描述

我正在构建一个应用程序,管理员可以在其中停用/激活任何员工。基本上,当我的页面加载每个员工的活动状态时,都会绑定到mat-table从 API 响应中获取。如果管理员通过另一个 API 调用停用/激活任何员工并且由于某种原因调用错误,我希望切换切换到以前的状态。

示例:我使用以下字段 从数据库emp1中获取员工数据: , , , , , (true/false)。现在,如果我从 true 切换到 false 或反之,我分别对 API 进行 HTTP 调用。如果该 API 调用因任何原因失败,用户应该会看到变量的原始状态。mat-tableidfnamemnamelnameroleactivestateactivestateactivestate

这是我在用户更改切换状态时调用的函数。

      /** Update employee is activated state*/
  updateEmployeeActiveState(e: any, empoyee: Employee, row) {
    console.log(row);
    var user = JSON.parse(localStorage.getItem('currentUser'));
    if (e.checked) {
      this.backendService.putEmployeeState(user.clientId, empoyee.employeeId, 1).subscribe(response => {

        this._snackBar.open(response.toString(), '', {
          duration: 3000,
          verticalPosition: 'bottom'
        });
      }, (error) => {

        this._snackBar.open("error -->"+error, '', {
          duration: 3000
        });
       this.dataSource.data[row].user.activeState = 0;
        
        
      });
    } else {
      this.backendService.putEmployeeState(user.clientId, empoyee.employeeId, 0).subscribe(response => {

        this._snackBar.open(response.toString(), '', {
          duration: 3000,
          verticalPosition: 'bottom'
        });
      }, (error)=> {

        this._snackBar.open("error -->"+error, '', {
          duration: 3000
        });
        this.dataSource.data[row].user.activeState = 1;
      });
    }
  }

模板代码:

<!-- Is Activated Column -->
<ng-container matColumnDef="activeState">
    <th mat-header-cell *matHeaderCellDef> Is Activated </th>
    <td mat-cell *matCellDef="let element; let rowNo = index;" data-title="User Name:"><mat-slide-toggle *ngIf="element.user?.userName" [checked]="element.user.activeState == 1" (change)="updateEmployeeActiveState($event, element, rowNo)" [(ngModel)]="element.user.activeState"></mat-slide-toggle></td>
  </ng-container>

请忽略row.user.activeState,因为我试图重新分配员工状态,但它不起作用。

标签: angulartypescriptangular-material

解决方案


问题

您的代码完全只处理一个问题

考虑以下两行

this.dataSource.data[row].user.activeState = 0;
...
this.dataSource.data[row].user.activeState = 1;

这些行不会触发更改检测。考虑添加一种触发更改检测的方法,例如使用扩展运算符(...)

  // Update employee is activated state
  updateEmployeeActiveState(e: any, empoyee: Employee, row) {
     const user = JSON.parse(localStorage.getItem('currentUser'));
     const activeState = e.checked ? 0 : 1
     this.backendService
       .putEmployeeState(user.clientId, empoyee.employeeId, activeState)
       .subscribe({
          next:() => {
             this._snackBar.open(response.toString(), '', {
               duration: 3000,
               verticalPosition: 'bottom'
              });
          },
          error: () => {
            this._snackBar.open("error -->"+error, '', {
              duration: 3000
           });
            // Change Back to initial state
            this.dataSource.data[row].user.activeState = !activeState;
            
            // Trigger change detection
            this.dataSource = [...this.dataSource]
          }
       })
  }


推荐阅读