There is a function in my codebase called getData()
that fetches data from an API. I am trying to call this function from a different component, which I will refer to as MainComponent and AnotherComponent for the sake of clarity:
import MainComponent from ./../main-component/main-component
...
export class AnotherComponent extends OnInit {
...
constructor(private _maincomp: MainComponent){}
onClick = () => {
this._maincomp.getData();
}
}
Although the data in the MainComponent property updates successfully, the view does not reflect these changes. How can I resolve this issue?
This is the html snippet from the MainComponent:
<div class="row table-container shadow rounded mt-4 ml-1">
<table mat-table class="data-table mat-elevation-z10" [dataSource]="datas">
<ng-container matColumnDef="Order ID">
<mat-header-cell class="header order-id-col" *matHeaderCellDef>Order ID</mat-header-cell>
<mat-cell class="order-id-col col-data" *matCellDef="let data">{{ data.order_id }}</mat-cell>
</ng-container>
//another ng-container goes here...
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</table>
</div>
Here is the .ts file for the MainComponent:
export class MainComponent implements OnInit {
displayedColumns = ['Order ID', 'Order By', 'Batch Kultur', 'Jenis Media', 'Jenis Vessel', 'Jumlah Ordered',
'Tanggal Order', 'Tanggal Pakai', 'Status', 'Action'];
datas;
filter;
constructor(private _service: DataModelService) { }
ngOnInit() {
this.getData();
}
getData = () => {
this._service.getData(1, 10, this.filter , 'media-request')
.subscribe(
res => {
this.datas = res.data.data;
},
err => {
console.log(err);
}
);
}
}
This is the AnotherComponent that invokes the MainComponent function:
import { MainComponent } from '../main-component/main-component.component';
export class MainComponent implements OnInit {
constructor(public _maincomp: MainComponent) { }
ngOnInit() {}
onClick = () => {
this._router.navigate([`dashboard/main-component`]);
setTimeout(() => {
this._maincomp.getData();
}, 1000)
}
}