我想在 loan-form.component.ts
提交新贷款时更新 loans.component.ts
中的数据源 .
所以在 loan-form.component.ts
中,我在表单提交时调用它
onSubmit() {
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
this.http
.post(this.getHostUrl(), JSON.stringify(this.model), config).subscribe();
this.loanAdded.emit(true);
}
哪里
@Output() loanAdded : EventEmitter<boolean> = new EventEmitter<boolean>();
然后在 loans-component.ts
我有
@Input()
set refreshData (value: boolean) {
this.refresh();
}
哪里
refresh() {
console.log('refresh');
this.getLoans().subscribe((loans) => {
this.loans = loans;
this.dataSource = new MatTableDataSource(loans);
this.dataSource.sort = this.sort;
this.changeDetectorRefs.detectChanges();
});
}
它有点工作,但它非常间歇 .
-
在Firefox和Edge中,它适用于第二次提交,然后看似随机
-
在Chrome中,它始终如一地运作
我也试过添加以下内容:
ngOnChanges(changes: SimpleChanges): void {
this.refresh();
}
ngOnInit() {
this.refresh();
}
ngAfterViewInit() {
this.refresh();
}
我可以在控制台中看到每当我提交表单时都会调用 refresh
,但网格并不总是得到更新...
我也有这种方法删除行然后更新,它完美地工作:
removeSelectedRows() {
this.selection.selected.forEach(item => {
// console.log(item);
this.http.delete(this.getHostUrl() + '/' + item.Id).subscribe();
});
this.ngOnChanges(null);
this.refresh();
this.selection = new SelectionModel<Loan>(true, []);
}
谁能指出我正确的方向?
1 回答
问题在这里:
this.http.post
本质上是异步的,this.loanAdded.emit
是同步的 .this.loanAdded.emit
甚至会在您收到this.http.post
的回复之前运行 . 所以要修复它,在subscribe
块中写入this.loanAdded.emit
. 像这样的东西:有了这个,你只有在你收到POST电话的回复后才会发出声音 . 因此,您将确保后端的DATA已更新 .