代码之家  ›  专栏  ›  技术社区  ›  Bassie

使用@Input属性一致更新子元素时遇到问题

  •  0
  • Bassie  · 技术社区  · 7 年前

    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 每次我提交表单时都会调用3次,但网格并不总是得到更新。。。

    我也有这个方法来删除行,然后更新,它工作得很好:

    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 回复  |  直到 7 年前
        1
  •  2
  •   SiddAjmera    7 年前

    问题在于:

    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 是同步的。

    这个 将在您收到来自的响应之前运行 这是http.post . 因此,要修复它,请编写 这个 subscribe 块大概是这样的:

    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呼叫的响应后发出信号。因此,您将确保后端上的数据已更新。

    推荐文章