首页 > 解决方案 > “无法读取未定义的属性‘selectedZones’”已初始化且非空变量

问题描述

我有一个组件使用 ngOnInit 中的选定区域过滤构建区域

rfid.component.ts

@Component(...)
export class RfidComponent implements OnInit {

  gridApi: GridApi;
  partList = new BehaviorSubject<IPart>(null);
  selectedZones: string[] = [];

  constructor(private zvSelectionService: ZvSelectionService) {
  }

  isInBuildZone(bom: IBomLine): boolean {
    return this.selectedZones.includes(bom.buildZone);
  }

  ngOnInit(): void {
    this.selectedZones = this.zvSelectionService.selectedZones.map(zone => zone.name);
    console.log(this.selectedZones) // -> ["LM3"]

    of(partList).pipe(
      map((list: IPart) => ({...list, bomLines: list.bomLines.filter(this.isInBuildZone)})),
      filter((list: IPart) => list.bomLines.length > 0),
    )
      .subscribe(data => this.partList.next(data));
  }
}

但我收到以下错误,即使 selectedZones 已初始化且不为空:

ERROR TypeError: Cannot read property 'selectedZones' of undefined
    at isInBuildZone (rfid.component.ts:50)
    at Array.filter (<anonymous>)
    ...

标签: javascriptangularrxjs

解决方案


您应该将调用的函数绑定到组件类

map((list: IPart) => ({...list, bomLines: list.bomLines.filter(this.isInBuildZone.bind(this))})),

推荐阅读