Sumchans
Sumchans

Reputation: 3774

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

I have the data pull perfectly working, but cannot get the reload work after a new record is added. According to my knowledge, whenever a next method is called on a behaviorsubject all the observers would get notified of it and data reload would happen autmatically. But not happening that way.

Component.ts

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

Here is the code called to post a new record

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

Upvotes: 1

Views: 4227

Answers (2)

user4676340
user4676340

Reputation:

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

Angular provides an abstraction of the data source, you're not supposed to fiddle in it.

Try using this instead.

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

Upvotes: 3

Pardeep Jain
Pardeep Jain

Reputation: 86740

Call you getRequest again after Posting new record to the server like this -

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

Upvotes: 1

Related Questions