我有调用API的函数来获取名为getData()
的数据。我以这种方式从另一个组件调用了该函数(为了便于阅读,我将组件名称更改为MainComponent和AnotherComponent):
import MainComponent from ./../main-component/main-component
...
export class AnotherComponent extends OnInit {
...
constructor(private _maincomp: MainComponent){}
onClick = () => {
this._maincomp.getData();
}
}
当我检查MainComponent属性中的数据时,它已经更改,但视图未更改。我该怎么解决?
以下是MainComponent上的html:
<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>
这是MainComponent的.ts文件:
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);
}
);
}
}
这是另一个在MainComponent中调用了函数的AnotherComponent:
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)
}
}
答案 0 :(得分:0)
尝试使用ChangeDetectorRef
:
constructor(
private cdRef: ChangeDetectorRef,
private _maincomp: MainComponent
) {}
onClick = () {
this._maincomp.getData();
this.cdRef.detectChanges();
}