MatTableDataSource - 当新记录添加到服务器时如何刷新 table

MatTableDataSource - how to refresh table when a new record is added to the server

我的数据拉取工作正常,但在添加新记录后无法重新加载。据我所知,每当在行为主体上调用 next 方法时,所有观察者都会收到通知,并且数据会自动重新加载。但不是那样发生的。

Component.ts

dataSource = new MatTableDataSource<IWorkOrders>();
  ngOnInit() {
    this.bs.wobSubject$.subscribe((data:IWorkOrders[]) => {
      this.dataSource.data = data;
    })

这是为 post 一条新记录调用的代码

this.bs.postWorkOrder(this.saleForm.value);

Service.ts

      public wobSubject$ = new BehaviorSubject<IWorkOrders[]>([]);
    constructor(private http: HttpClient) {
     this.getWorkOrder(); 
    }
      getWorkOrder() {
        this.http.get(this.BASE_URL + '/getworkorders/')
        .subscribe((data:IWorkOrders[]) => {
          this.wobSubject$.next(data);
        });
      }
  postWorkOrder(workOrder: IWorkOrders) {
    this.http.post<IWorkOrders>(this.BASE_URL + '/addworkorder/', workOrder)
    .subscribe((data: any) => {
      this.wobSubject$.next(data);
    });
  }

像这样将新记录发布到服务器后再次调用您getRequest -

 getWorkOrder() {
        this.http.get(this.BASE_URL + '/getworkorders/')
        .subscribe((data:IWorkOrders[]) => {
          this.wobSubject$.next(data);
        });
      }
  postWorkOrder(workOrder: IWorkOrders) {
    this.http.post<IWorkOrders>(this.BASE_URL + '/addworkorder/', workOrder)
    .subscribe((data: any) => {
      this.getWorkOrder()
    });
  }
this.bs.wobSubject$.subscribe((data:IWorkOrders[]) => {
  this.dataSource.data = data;
})

Angular 提供数据源的抽象,您不应该在其中 fiddle。

试试改用这个。

this.bs.wobSubject$.subscribe((data:IWorkOrders[]) => {
  this.dataSource = new MatTableDataSource(data);
})