首页 > 解决方案 > Angular如何在单击时刷新可观察的数据

问题描述

我正在尝试在单击时从我的 Observable 刷新我的数据

这是我的代码我的父组件

export class StepComponent implements OnInit, AfterViewInit{

  displayedColumns: string[] = ['dateCreation','siteName', 'adress'/*,'enseigne'*/, 'postCode', 'commune','prestation', 'validation'];

  dataset! : DataTable[];

  @ViewChild(ButtonComponent) bhuttonChild!: ButtonComponent;

  constructor(private dataTableService : DataTableService) { }

  ngAfterViewInit(): void {
  }

  ngOnInit(): void {
    this.dataTableService.fetchDataTableNewPrestation().subscribe(r => this.dataset = r); // I would like to refresh this data with the event of the buttonChild

  }
}

step.html(父组件)

<table class="table" mat-table [dataSource]="dataset">
[...]

      <ng-container matColumnDef="validation">
        <th mat-header-cell *matHeaderCellDef> Validation </th>
        <mat-cell mat-cell *matCellDef="let element">
          <app-button [element]="element"></app-button>
        </mat-cell>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

这是我的子组件,它是一个按钮:

@Component({
  selector: 'app-button',
  template: `
      <div  *ngIf="element.id"  >
        <button mat-raised-button [value]="false" (click)="initTaskOnPrestation(false)" color="primary">Normal</button>
        <button mat-raised-button [value]="true" (click)="initTaskOnPrestation(true)" color="warn">Urgent</button>
      </div>

  `,
  styleUrls: ['./button.component.scss']
})
export class ButtonComponent implements OnInit, AfterViewInit {

  @Input() element!: Prestation;
  urgent!: boolean

  @Input() lastStatus!: number;
  statusHistory!: StatusHistory;

  @ViewChild('button')
  button!: ElementRef;

  constructor(private taskService : TaskService) { }

  ngAfterViewInit(): void {
  }

  ngOnInit(): void {
    
  }

  initTaskOnPrestation(bool : boolean){
    this.prestation.urgency = bool;
    this.taskService.initTaskOnPrestation(this.prestation);
  }

}

我的按钮需要发送一个请求,该请求将在我的后端更改我的数据,但是我需要使用该方法从我的 StepComponent 重新加载数据fetchDataTableNewPrestation()

我正在尝试让按钮事件来使用它,但即使在多次检查Rxjs 文档后我也不知道该怎么做

标签: angularobservablerxjs-observables

解决方案


您可以使用@Output通知父组件需要重新加载数据:

在子组件中:

export class ButtonComponent implements OnInit, AfterViewInit {
  @Output() dataChanged: EventEmitter<any> = new EventEmitter();
  initTaskOnPrestation(bool : boolean){
    this.prestation.urgency = bool;
    this.taskService.initTaskOnPrestation(this.prestation);
    this.dataChanged.emit(this.prestation);
  }
}

在父组件 HTML 中:

<mat-cell mat-cell *matCellDef="let element">
    <app-button [element]="element" (dataChanged)="reloadData($event)"></app-button>
 </mat-cell>

在父组件打字稿中:

export class StepComponent implements OnInit, AfterViewInit{
  ngOnInit(): void {
    this.reloadData();
  }
  reloadData() {
    this.dataTableService.fetchDataTableNewPrestation().subscribe(r => this.dataset = r);
  }
}

推荐阅读