首页 文章

无法使用@Input属性持续更新子元素

提问于
浏览
0

我想在 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 回答

  • 2

    问题在这里:

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

    this.http.post 本质上是异步的, this.loanAdded.emit 是同步的 .

    this.loanAdded.emit 甚至会在您收到 this.http.post 的回复之前运行 . 所以要修复它,在 subscribe 块中写入 this.loanAdded.emit . 像这样的东西:

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

    有了这个,你只有在你收到POST电话的回复后才会发出声音 . 因此,您将确保后端的DATA已更新 .

相关问题