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

Mat-autocomplete在ngOnInit首次加载失效:map读取null属性报错

问题解决:Angular Mat-autocomplete首次加载报错“无法读取null的属性'map'”

错误原因

你在ngOnInit中直接执行this.AmenityList.map(...),但AmenityList是通过订阅infoService.AmenityList异步获取数据的。组件首次加载时,订阅回调还未执行,AmenityList处于null或undefined状态,调用map方法自然会触发报错。

解决方案

方案1:将依赖异步数据的逻辑移入订阅回调

把displayName赋值和filteredOptions的初始化代码放到订阅内部,确保只有当AmenityList有值后才执行这些逻辑:

ngOnInit(): void {
  this.infoService.AmenityList.subscribe((res)=>{
      this.AmenityList = res; 
      this.assignForm.push(this.createForm(1))
      this.dataSource = [...this.assignForm.controls];
      console.log(this.dataSource.END_TIME , "data");
      
      // 移到订阅内部,确保AmenityList已赋值
      this.displayName = this.AmenityList.map(a=>a.DISPLAY_NAME);
      this.filteredOptions = this.myControl.valueChanges.pipe(
        startWith(''),
        map(value => this._filter(value || '')),
      );
    })
}

方案2:初始化AmenityList为空数组(增强代码健壮性)

在组件类中提前初始化AmenityList为空数组,即使订阅还未返回数据,调用map方法也不会报错:

// 组件类属性声明
AmenityList: any[] = [];

ngOnInit(): void {
  this.infoService.AmenityList.subscribe((res)=>{
      this.AmenityList = res; 
      this.assignForm.push(this.createForm(1))
      this.dataSource = [...this.assignForm.controls];
      console.log(this.dataSource.END_TIME , "data");
      
      // 数据更新后同步更新相关逻辑
      this.displayName = this.AmenityList.map(a=>a.DISPLAY_NAME);
      this.filteredOptions = this.myControl.valueChanges.pipe(
        startWith(''),
        map(value => this._filter(value || '')),
      );
    })
}

注意:方案2中需在订阅回调内重新更新displayName和filteredOptions,否则下拉选项不会随异步数据更新而变化,因此更推荐方案1。

额外提醒

你的HTML中同时使用了[formControl]和[(ngModel)],虽然Angular支持这种混合模式,但需确保已导入ReactiveFormsModule和FormsModule,且逻辑上不会产生冲突。如果使用纯响应式表单,建议只保留[formControl],避免双向绑定带来的潜在问题。

内容的提问来源于stack exchange,提问作者Neeti Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:40:17