You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular绑定Kendo Grid遇类型错误:'T[] | null'无法赋值给'any[]'

解决Angular中Kendo Grid绑定async数据流的类型错误

问题原因

async管道在Observable未发出任何值前会返回null,而Kendo Grid的kendoGridBinding属性要求接收非null的数组类型。你的代码中,当products$使用EMPTY处理错误时,Observable不会发出任何值,导致data.products始终为null,触发类型不匹配错误。

解决方案

提供三种可行的修复方式,按需选择:

方案1:直接在*ngIf中绑定数据流(最简洁)

修改模板,直接将async管道的结果赋值给变量,*ngIf会自动过滤null/undefined,确保渲染时products是有效的数组:

<ng-container *ngIf="products$|async as products">
  <kendo-grid
    [kendoGridBinding]="products"
    [height]="400"
    [pageable]="true"
    [pageSize]="10"
  >
    <!-- 你的列配置 -->
  </kendo-grid>
</ng-container>

方案2:使用空值合并操作符兜底

如果需要保留对象包裹的写法,给data.products添加空值合并操作符??,当值为null时返回空数组,满足kendoGridBinding的类型要求:

<ng-container *ngIf="{products: products$|async} as data">
  <kendo-grid
    [kendoGridBinding]="data.products ?? []"
    [height]="400"
    [pageable]="true"
    [pageSize]="10"
  >
    <!-- 你的列配置 -->
  </kendo-grid>
</ng-container>

方案3:修改Observable的错误处理逻辑

在组件的数据流中,用of([])替代EMPTY,这样即使发生错误,Observable也会发出一个空数组,async管道不会返回null:

// app.component.ts
import { of } from 'rxjs';

products$ = this.productsService.products$
.pipe(
  catchError(err => {
    this.errorMessage = err;
    return of([]); // 发出空数组而非EMPTY
  })
);

额外说明

EMPTY是一个不发出任何next值的Observable,只会发出complete信号,因此async管道会一直保持null状态。而of([])会主动发出一个空数组,让async管道能拿到有效的数组类型值。

内容的提问来源于stack exchange,提问作者sam sergiy klok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:13:38