Angular Material mat-table 通过服务取列值重复执行及TS报错处理
问题根源分析
- 当前实现会反复执行逻辑,核心原因是把带HTTP订阅的
getValueOfInterfaceB方法直接写在模板表达式{{}}中,Angular每次触发变更检测时都会调用该方法,导致重复发起接口B的请求。 - 之前尝试第三方方案时的TS报错,本质是语法书写错误,把类型注解的位置写错了。
原英文报错对应中文翻译
error TS2304: 找不到名称“res”。对应原错误行res[] => {error TS1011: 元素访问表达式应接收一个参数。对应原错误行res[] => {error TS1005: 应为“,”。对应原错误行res[] => {error TS18004: 作用域内不存在“res”的简写属性对应的值。请先声明res或为其提供初始值。对应原错误行res.forEach((value,index)=>{error TS2769: 与此调用匹配的任何重载都不符合。对应原错误行res.forEach((value,index)=>{
正确实现方案
核心思路
不要在模板中调用带请求逻辑的方法,预先在组件内完成接口A数据、接口B数据的关联,配合缓存避免重复发请求,模板仅通过异步管道渲染结果。
代码实现
1. 组件TypeScript代码
// 导入需要的Angular依赖 import { MatTableDataSource } from '@angular/material/table'; import { Observable, of } from 'rxjs'; import { tap, map } from 'rxjs/operators'; // 接口A返回的行数据类型 interface RowDataType { id: number; // 其他接口A返回的字段 } // 接口B返回的数据类型 interface Entry { title: string; // 其他接口B返回的字段 } @Component({ selector: 'app-table', templateUrl: './table.component.html' }) export class TableComponent { // 表格数据源 dataSource: MatTableDataSource<RowDataType>; // 缓存已请求过的id对应的标题,避免重复发请求 private titleCache = new Map<number, string>(); // 存储每行id对应的标题可观察对象,供模板异步管道使用 rowTitleMap = new Map<number, Observable<string>>(); constructor(private entrieService: EntrieService) {} // 页面加载时调用该方法获取表格数据 loadTableData() { // 先请求接口A的原始表格数据 this.apiService.getTableData().subscribe((rows: RowDataType[]) => { // 遍历每一行,预处理标题对应的数据源 rows.forEach(row => { // 命中缓存,直接返回缓存的标题 if (this.titleCache.has(row.id)) { this.rowTitleMap.set(row.id, of(this.titleCache.get(row.id)!)); return; } // 未命中缓存,请求接口B,拿到结果后写入缓存 const title$ = this.entrieService.getEntries({ Id: row.id }).pipe( map((entries: Entry[]) => entries[0]?.title || ''), tap(title => this.titleCache.set(row.id, title)) ); this.rowTitleMap.set(row.id, title$); }); // 赋值给表格数据源,触发渲染 this.dataSource = new MatTableDataSource(rows); }); } }
2. 模板HTML代码
<mat-table [dataSource]="dataSource"> <!-- 其他列定义省略 --> <ng-container matColumnDef="title"> <mat-header-cell *matHeaderCellDef> Title</mat-header-cell> <!-- 仅通过预先生成的可观察对象配合异步管道渲染,不调用方法 --> <mat-cell *matCellDef="let element"> {{ rowTitleMap.get(element.id) | async }} </mat-cell> </ng-container> <!-- 其他列定义省略 --> </mat-table>
原TS报错的修正说明
之前写错的代码行res[] => {属于完全语法错误:
- 没有提前声明
res变量就直接使用 - 错误把泛型类型注解写在了箭头函数的前面,正确的类型写法应该是写在回调函数的参数位置,比如上面代码中的
map((entries: Entry[]) => ...),参数和类型用括号包裹,箭头函数在参数括号后面。
内容的提问来源于stack exchange,提问作者htp15
相关产品推荐
相关产品推荐

