Angular Material mat-grid-list rowHeight属性TypeScript编译错误求助
解决Angular mat-grid-list rowHeight编译错误
问题根源
你的代码中catchError操作符直接返回字符串"500px",但catchError要求返回Observable类型的值,这会导致rowHeight的Observable类型推断异常,最终让async管道可能输出null,与mat-grid-list的rowHeight属性要求的string | number类型不匹配,触发编译错误。
修复方案
方案1:修正catchError返回值
在catchError中用of()操作符包裹默认值,返回合法的Observable:
import { of } from 'rxjs'; // 其他必要导入... rowHeight = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(({ matches }) => { if (matches) { return "1500px"; } return "500px"; }), startWith("500px"), catchError(_ => of("500px")) // 返回Observable类型 );
方案2:模板层添加空值兜底
如果不想修改组件逻辑,可在模板中用??空值合并操作符,强制返回合法类型:
<mat-grid-list cols="2" [rowHeight]="(rowHeight | async) ?? '500px'">
方案3:双重保障(推荐)
同时使用上述两种方式,既保证Observable类型正确,又在模板层做兜底:
组件代码:
import { of } from 'rxjs'; import { map, startWith, catchError } from 'rxjs/operators'; // 其他必要导入... rowHeight = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(({ matches }) => matches ? "1500px" : "500px"), startWith("500px"), catchError(_ => of("500px")) );
模板代码:
<mat-grid-list cols="2" [rowHeight]="(rowHeight | async) ?? '500px'">
内容的提问来源于stack exchange,提问作者miaoz2001
相关产品推荐
相关产品推荐

