为什么我的Angular Material表格在数据源更改时不更新?

huangapple go评论54阅读模式
英文:

Why doesn't my Angular Material table update when the data source is changed?

问题

我使用mat-table来让用户查看应用程序的公司连接对象列表。

问题出现在用户点击编辑按钮并使用模态框更新公司连接时,表格没有反映出变化。

为了排除故障,我已经在多个地方将更新后的对象打印到控制台,并确认对象正在更新,似乎只是表格没有更新。

表格组件的HTML部分:

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z4">
  <!-- 列定义 -->
  <ng-container matColumnDef="DattoDomain">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Datto 域名 </th>
    <td mat-cell *matCellDef="let company"> {{company.dattoDomain}} </td>
  </ng-container>
  <ng-container matColumnDef="connectWiseId">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> ConnectWise ID </th>
    <td mat-cell *matCellDef="let company"> {{company.connectWiseId}} </td>
  </ng-container>
  <ng-container matColumnDef="actions">
    <th mat-header-cell *matHeaderCellDef>操作</th>
    <td mat-cell *matCellDef="let company">
      <button mat-icon-button (click)="openEditCompanyModal(company)">
        <mat-icon>edit</mat-icon>
      </button>
    </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

表格组件的 TypeScript 部分:

export class CompanyTableComponent implements OnInit, AfterViewInit {
  @ViewChild(MatSort) sort: MatSort;
  @Input() companies: CompanyConnection[];
  @Input() getError: boolean; 
  displayedColumns: string[] = ['DattoDomain', 'connectWiseId', 'actions'];
  companies$: Observable<CompanyConnection[]> = of([]);
  dataSource = new MatTableDataSource<CompanyConnection>();

  constructor(
    private companyDataService: CompanyDataService,
    private dialog: MatDialog,
    private changeDetectorRef: ChangeDetectorRef
  ) {}

  ngOnInit() {
    if (this.getError) {
      this.companies$ = this.companyDataService.getErrorCompanyConnections();
    } else {
      this.companies$ = this.companyDataService.getHealthyCompanyConnections();
    }
    this.companies$.subscribe((companies: CompanyConnection[]) => {
      this.dataSource.data = companies;
      this.changeDetectorRef.detectChanges();
    });
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

  openEditCompanyModal(company: CompanyConnection) {
    const dialogRef = this.dialog.open(CompanyModalComponent, {
      data: { company }
    });
  
    dialogRef.afterClosed().subscribe((editedCompany: CompanyConnection) => {
      if (editedCompany) {
        // 更新现有的公司连接
        this.companyDataService.editCompanyConnection(editedCompany).subscribe(
          () => {},
          error => {}
        );
  
        // 检索更新后的公司连接
        this.companyDataService.getCompanyConnection(editedCompany.dattoDomain).subscribe(
          (updatedCompany: CompanyConnection | undefined) => {
            if (updatedCompany) {
              console.log('更新后的公司连接:', updatedCompany);
            } else {
              console.log('未找到公司连接');
            }
          },
          error => {
            console.log('检索公司连接时出错:', error);
          }
        );
      } 
    });
  }
}

这个文件返回:更新后的公司连接:{dattoDomain: 'aptdynamics', connectWiseId: 'Bucks Communications', status: '200'}

这是来自 company-connection-service.service.ts 文件的一些方法。如果有其他能帮助的代码,请告诉我!

感谢!

英文:

I am using a mat-table so users can see a list of companyConnection objects for an application.

My issue occurs when a user clicks the edit button and updates a companyConnection using a modal, but the change does not reflect in the table.

For troubleshooting, I have printed the updated object to the console in multiple spots and have confirmed that the object is being updated, and it seems to just be a problem with the table not updating.

table.component.html


&lt;table mat-table [dataSource]=&quot;dataSource&quot; matSort class=&quot;mat-elevation-z4&quot;&gt;
&lt;!-- Columns --&gt;
&lt;ng-container matColumnDef=&quot;DattoDomain&quot;&gt;
&lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt; Datto Domain &lt;/th&gt;
&lt;td mat-cell *matCellDef=&quot;let company&quot;&gt; {{company.dattoDomain}} &lt;/td&gt;
&lt;/ng-container&gt;
&lt;ng-container matColumnDef=&quot;connectWiseId&quot;&gt;
&lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt; ConnectWise Id &lt;/th&gt;
&lt;td mat-cell *matCellDef=&quot;let company&quot;&gt; {{company.connectWiseId}} &lt;/td&gt;
&lt;/ng-container&gt;
&lt;ng-container matColumnDef=&quot;actions&quot;&gt;
&lt;th mat-header-cell *matHeaderCellDef&gt;Actions&lt;/th&gt;
&lt;td mat-cell *matCellDef=&quot;let company&quot;&gt;
&lt;button mat-icon-button (click)=&quot;openEditCompanyModal(company)&quot;&gt;
&lt;mat-icon&gt;edit&lt;/mat-icon&gt;
&lt;/button&gt;
&lt;/td&gt;
&lt;/ng-container&gt;
&lt;tr mat-header-row *matHeaderRowDef=&quot;displayedColumns&quot;&gt;&lt;/tr&gt;
&lt;tr mat-row *matRowDef=&quot;let row; columns: displayedColumns;&quot;&gt;&lt;/tr&gt;
&lt;/table&gt;
export class CompanyTableComponent implements OnInit, AfterViewInit {
@ViewChild(MatSort) sort: MatSort;
@Input() companies: CompanyConnection[];
@Input() getError: boolean; 
displayedColumns: string[] = [&#39;DattoDomain&#39;, &#39;connectWiseId&#39;, &#39;actions&#39;];
companies$: Observable&lt;CompanyConnection[]&gt; = of([]);
dataSource = new MatTableDataSource&lt;CompanyConnection&gt;();
constructor(
private companyDataService: CompanyDataService,
private dialog: MatDialog,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnInit() {
if (this.getError) {
this.companies$ = this.companyDataService.getErrorCompanyConnections();
} else {
this.companies$ = this.companyDataService.getHealthyCompanyConnections();
}
this.companies$.subscribe((companies: CompanyConnection[]) =&gt; {
this.dataSource.data = companies;
this.changeDetectorRef.detectChanges();
});
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
openEditCompanyModal(company: CompanyConnection) {
const dialogRef = this.dialog.open(CompanyModalComponent, {
data: { company }
});
dialogRef.afterClosed().subscribe((editedCompany: CompanyConnection) =&gt; {
if (editedCompany) {
// Update the existing company connection
this.companyDataService.editCompanyConnection(editedCompany).subscribe(
() =&gt; {},
error =&gt; {}
);
// Retrieve the updated company connection
this.companyDataService.getCompanyConnection(editedCompany.dattoDomain).subscribe(
(updatedCompany: CompanyConnection | undefined) =&gt; {
if (updatedCompany) {
console.log(&#39;Updated company connection:&#39;, updatedCompany);
} else {
console.log(&#39;Company connection not found&#39;);
}
},
error =&gt; {
console.log(&#39;Error retrieving company connection:&#39;, error);
}
);
} 
});
}
}

this file returns: Updated company connection: {dattoDomain: &#39;aptdynamics&#39;, connectWiseId: &#39;Bucks Communications&#39;, status: &#39;200&#39;}

Here are methods from the company-connection-service.service.ts file

  export class CompanyDataService {
private companies: CompanyConnection[] = [
{
dattoDomain: &quot;aptdynamics&quot;, 
connectWiseId: &quot;Apartment Dynamics&quot;,
status: &quot;200&quot;
},
{
dattoDomain: &quot;buckscomm&quot;, 
connectWiseId: &quot;Bucks Communications&quot;,
status: &quot;200&quot;
},
{
dattoDomain: &quot;cardinalconcretecompany&quot;, 
connectWiseId: &quot;Cardinal Concrete Company&quot;,
status: &quot;200&quot;
},
{
dattoDomain: &quot;centralcarolinaseeding&quot;, 
connectWiseId: &quot;Central Carolina Seeding&quot;,
status: &quot;404&quot;
},
];
private companiesSubject = new BehaviorSubject&lt;CompanyConnection[]&gt;(this.companies);
constructor() { }
getCompanyConnections(): Observable&lt;CompanyConnection[]&gt; {
return this.companiesSubject.asObservable();
}
getCompanyConnection(dattoDomain: string): Observable&lt;CompanyConnection | undefined&gt; {
return this.getCompanyConnections().pipe(
map((companies: CompanyConnection[]) =&gt; {
return companies.find((company: CompanyConnection) =&gt; {
return company.dattoDomain === dattoDomain;
});
})
);
}
getHealthyCompanyConnections(): Observable&lt;CompanyConnection[]&gt; {
return this.getCompanyConnections().pipe(
map((companies: CompanyConnection[]) =&gt; {
return companies.filter((company: CompanyConnection) =&gt; {
return company.status === &quot;200&quot;;
});
})
);
}
getErrorCompanyConnections(): Observable&lt;CompanyConnection[]&gt; {
return this.getCompanyConnections().pipe(
map((companies: CompanyConnection[]) =&gt; {
return companies.filter((company: CompanyConnection) =&gt; {
return company.status !== &quot;200&quot;;
});
})
);
}
addCompanyConnection(company: CompanyConnection): Observable&lt;CompanyConnection[]&gt; {
this.companies.push(company);
this.companiesSubject.next(this.companies);
return of(this.companies);
}
editCompanyConnection(updatedCompany: CompanyConnection): Observable&lt;CompanyConnection[]&gt; {
const index = this.companies.findIndex(c =&gt; c.dattoDomain === updatedCompany.dattoDomain);
if (index !== -1) {
this.companies[index] = updatedCompany;
}
return of(this.companies);
}
}

if there is any other code I can provide that would help, please let me know!

Thanks!

答案1

得分: 0

在更新后,在主题上调用next

editCompanyConnection(updatedCompany: CompanyConnection): Observable<CompanyConnection[]> {
  const index = this.companies.findIndex(c => c.dattoDomain === updatedCompany.dattoDomain);
  if (index !== -1) {
    this.companies[index] = updatedCompany;
    this.companiesSubject.next(this.companies);    //添加这行
  }

  return of(this.companies);
}
英文:

Call next on the subject after updating.

  editCompanyConnection(updatedCompany: CompanyConnection): Observable&lt;CompanyConnection[]&gt; {
const index = this.companies.findIndex(c =&gt; c.dattoDomain === updatedCompany.dattoDomain);
if (index !== -1) {
this.companies[index] = updatedCompany;
this.companiesSubject.next(this.companies);    //add this line
}
return of(this.companies);
}

huangapple
  • 本文由 发表于 2023年6月2日 10:15:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定