Angular ng-select绑定BehaviourSubject异步数据为空问题
问题排查与修复方案
核心问题:模板字段引用不匹配
你的品牌数据结构仅包含entityID和label字段,但在<ng-template>选项模板中错误使用了{{item.name}},导致选项内容为空,ng-select无法识别有效选项,因此显示“未找到项目”。
具体修复步骤
1. 修正模板字段引用
将模板中的item.name替换为item.label,与你的品牌数据结构对齐:
<ng-select [items]="brands$ | async" placeholder="Marques" [(ngModel)]="selectedBrands" bindLabel="label" [multiple]="true" class="input-field"> <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index"> <input id="item-{{index}}" type="checkbox" [ngModel]="item$.selected"/> {{item.label}} </ng-template> </ng-select>
2. 优化Observable订阅(可选)
你无需额外创建brands$ BehaviorSubject,直接复用服务中的pss.brands$即可,减少冗余订阅:
@Component({ selector: 'app-product-grid', templateUrl: './product-grid.component.html', styleUrls: ['./product-grid.component.css'] }) export class ProductGridComponent implements OnInit { // 直接声明为Observable,无需自己维护BehaviorSubject brands$: Observable<Brand[]>; selectedBrands: Brand[] = [] constructor(private pss: ProductStoreService){} ngOnInit(): void { this.brands$ = this.pss.brands$; } }
甚至可以直接在模板中使用[items]="pss.brands$ | async",省去组件内的赋值步骤。
3. 确认bindLabel配置有效性
你的bindLabel="label"配置是正确的,与品牌数据中的label字段匹配,无需修改。
完成以上修改后,下拉列表即可正常加载9个品牌选项。
内容的提问来源于stack exchange,提问作者ValLeNain
相关产品推荐
相关产品推荐

