CRUD后重新加载页面

时间:2019-09-30 20:09:40

标签: javascript angular api

我正在寻找一种对用户透明的CRUD操作后重新加载页面的方法。

实际上,在创建或删除之后,我必须重新加载页面以显示我的操作。

我使用api来实现此功能,当我将其与json文件一起使用时,它可以正常工作。

谢谢

删除示例:

  dataSource = new MatTableDataSource();
  displayedColumns = ['first_name', 'middle_name', 'last_name', 'mail', 'role', 'action'];
  action: any;
  selectedUser: User;
  @Input() user: User;
  data: any;


  @ViewChild(MatSort, {static: true}) sort: MatSort;
  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  constructor(private formBuilder: FormBuilder, private userService: UserService, public dialog: MatDialog) {
  }

  ngOnInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;

    this.userService.getUsers()
      .subscribe(
        (response) => {
          this.dataSource.data = response;
        },
        (error) => {
          console.log('error ' + error);
        }
      );
  }

  onDelete(selectedUser){
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.value) {
        this.userService.delete(selectedUser.id).subscribe(res => {
          this.dataSource.data.splice(selectedUser.id, 1);
        });
        Swal.fire(
          'Deleted!',
          'User has been deleted.',
          'success'
        )
      }
    })
  }

html代码

让我知道您是否需要更多代码以及代码的哪一部分。

  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource" matSort multiTemplateDataRows >

      <!-- First name Column -->
      <ng-container matColumnDef="first_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> First name </th>
        <td mat-cell *matCellDef="let element"> {{element.first_name}} </td>
        <label>
          <input class="table-input" *ngIf="selectedUser" type="text">
        </label>
      </ng-container>

      <!-- Middle name Column -->
      <ng-container matColumnDef="middle_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Middle name </th>
        <td mat-cell class="status" *matCellDef="let element">{{element.middle_name}}</td>
      </ng-container>

      <!-- Last name Column -->
      <ng-container matColumnDef="last_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Last name </th>
        <td mat-cell *matCellDef="let element"> {{element.last_name}} </td>
      </ng-container>

      <!-- Email Column -->
      <ng-container matColumnDef="mail">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Email </th>
        <td mat-cell *matCellDef="let element"> {{element.mail}} </td>
      </ng-container>

      <!-- Role Column -->
      <ng-container matColumnDef="role">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Role </th>
        <td mat-cell *matCellDef="let element"> {{getRole(element)}} </td>
      </ng-container>

      <!-- Actions Column -->
      <ng-container matColumnDef="action">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Actions </th>
        <td mat-cell *matCellDef="let row">
          <button mat-raised-button color="primary" class="editUserBtn" (click)="openEditDialog(row)"><mat-icon class="edit-icon" >launch</mat-icon><span>Edit</span></button>
          <button mat-raised-button color="warn" class="deleteUserBtn" (click)="onDelete(row)"><mat-icon class="delete-icon" >delete_outline</mat-icon><span>Delete</span></button>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
    <mat-paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
  </div>
</div>

3 个答案:

答案 0 :(得分:1)

在这种情况下,您将必须使用BehaviorSubjectBehaviorSubject会继续收听订户,并在发出next时进行更新。

dataSource: BehaviorSubject<MatTableDataSource[]> = new BehaviorSubject([]);

onDelete(selectedUser) {
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!'
  }).then(result => {
    if (result.value) {
      this.userService.delete(selectedUser.id).subscribe(res => {
        this.dataSource.value.data.splice(selectedUser.id, 1);
        this.dataSource.next(this.dataSource.value);
      });
      Swal.fire('Deleted!', 'User has been deleted.', 'success');
    }
  });
}

其中MatTableDataSource应该是您的数据类型。

答案 1 :(得分:0)

要刷新物料数据表,最简单的方法是刷新整个数据源:

 dataSource = new MatTableDataSource();
  displayedColumns = ['first_name', 'middle_name', 'last_name', 'mail', 'role', 'action'];
  action: any;
  selectedUser: User;
  @Input() user: User;
  data: any;


  @ViewChild(MatSort, {static: true}) sort: MatSort;
  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  constructor(private formBuilder: FormBuilder, private userService: UserService, public dialog: MatDialog) {
  }

  ngOnInit() {
    this.loadDataTable();
  }

  loadDataTable() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;

    this.userService.getUsers()
      .subscribe(
        (response) => {
          this.dataSource.data = response;
        },
        (error) => {
          console.log('error ' + error);
        }
      );
  }

  onDelete(selectedUser){
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.value) {
        this.userService.delete(selectedUser.id).subscribe(res => {
          this.loadDataTable();
          Swal.fire(
            'Deleted!',
            'User has been deleted.',
            'success'
          );
        },
        // Probably you want to add some error handling here:
        (error) => {
          console.error(error);
        });
      }
    })

答案 2 :(得分:0)

使用获取通话删除通话设置为管道。

      deleteUser(){ // called on click of delete
         this.userSvc
          .deleteUser() // service function that deletes a user. Could be any of CUD (Create, Update or Delete
          .pipe(   
            switchMap(data => this.userSvc.getUsers()) // pipe the result and perform retrieve.
           )
        .subscribe( result => this.users = result); // finally set the result on a field to show on the component template.    
    }

这里是一个快速示例https://stackblitz.com/edit/angular-agpxba?embed=1&file=src/app/app.component.ts

还有其他方法可以实现相同目的,特别是如果我们使用ngrx之类的应用程序状态管理框架。我们可能会识别状态已更改并触发检索API。这里的一个很简单。 15分钟内即可对样本进行快速编码。