从NgRx Observable到Angular输入信号:为何接收不到值?
问题原因
async管道在Observable发出第一个有效值前,会先发射null。而你定义的toolbarCustomConfig = input()是必填输入信号,Angular对必填输入有严格校验:一旦传入null或undefined,就会触发NG0911错误,导致组件无法正常接收后续的有效值。
修复方案
有两种方式可以解决这个问题:
方式一:为输入信号设置默认值
和原来的@Input定义对齐,明确允许输入null并设置初始默认值:
import { input } from '@angular/core'; import { ToolbarKendoState } from './your-types-path'; toolbarCustomConfig = input<ToolbarKendoState | null>(null);
方式二:标记为可选输入
如果不需要强制要求传入该值,可以显式将输入设为可选:
toolbarCustomConfig = input<ToolbarKendoState | null>({ required: false });
额外优化建议
如果你的Observable可能长时间没有发射值,建议在模板中用*ngIf过滤掉null状态,只在有有效值时渲染子组件:
<lib-product-config-toolbar *ngIf="toolbarConfig$ | async as config" [toolbarCustomConfig]="config" ></lib-product-config-toolbar>
内容的提问来源于stack exchange,提问作者Bartek
相关产品推荐
相关产品推荐

