簡體   English   中英

CRUD 后重新加載頁面

[英]Reload page after CRUD

我正在尋找一種在對用戶透明的 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>

在這種情況下,您將不得不使用BehaviorSubject BehaviorSubject會持續監聽訂閱者並在有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 應該是您的數據類型。

要刷新材料數據表,最簡單的方法是刷新整個數據源:

 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);
        });
      }
    })

Pipe 使用get 調用刪除調用。

      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

還有其他方法可以實現相同的目的,特別是如果我們使用 Application State 管理框架,如ngrx。 我們可以識別 state 已更改並觸發檢索 API。 這里的一個很簡單。 樣品在 15 分鍾內被快速編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM