【问题标题】:Cannot read property 'map' of undefined using D3 Bar Chart in Angular 7无法使用 Angular 7 中的 D3 条形图读取未定义的属性“地图”
【发布时间】:2026-02-16 20:30:02
【问题描述】:

当我映射 totalStores 对象时,无法读取未定义的属性“映射”。

我已将现有 JSON 数据解析为两个变量 store 和 storeCount,分别为 X 轴存储对象和 Y 轴存储对象

ngOnInit() {
    this.DashboardService.getActiveProjectsStatusByDimension(
      this.statusIndex,
      this.dimension
    ).subscribe(res => {
      this.res = res;
      this.projectSelectedDimension = JSON.parse(JSON.stringify(res));

      this.totalStores = Array();

      var storeCountIndex = 2;

      for (let k = 0; k < this.projectSelectedDimension.data.length; k++) {
        let obj = this.projectSelectedDimension.data[k];
        let xAxis = Object.keys(obj)[0];
        let yAxis = obj[Object.keys(obj)[0]][storeCountIndex];
        // console.log("x:", xAxis);
        // console.log("y:", yAxis);
        let objBarChart = { store: xAxis, storeCount: yAxis };
        this.totalStores.push(objBarChart);
      }

    });

    this.initAxis();
  }


private initAxis() {
    this.x = d3Scale
      .scaleBand()
      .rangeRound([0, this.width])
      .padding(0.1);
    this.y = d3Scale.scaleLinear().rangeRound([this.height, 0]);
    this.x.domain(this.totalStores.map(d => d.store));
    this.y.domain([
      0,
      d3Array.max(this.totalStores, this.totalStores.map(d => d.storeCount))   // erroe saying valueof is not a function
    ]);
  }


【问题讨论】:

  • 我认为totalStoresundefined 因为它被初始化(通过`this.totalStores = Array();) only when subscribe` 回调被执行:initAxis 在@987654328 之后立即被调用@invocation...尝试在订阅主体的末尾调用initAxis,例如在for循环之后...
  • 不,这不是任何问题的重复

标签: javascript angular typescript d3.js


【解决方案1】:

.subscribe() 函数内的代码在 getActiveProjectsStatusByDimension() 函数返回后运行。所以你试图映射一个未定义的对象。要解决这个问题,只需将 initAxis() 函数放在 subscribe 块中即可。

ngOnInit() {
    this.DashboardService.getActiveProjectsStatusByDimension(
      this.statusIndex,
      this.dimension
    ).subscribe(res => {
      this.res = res;
      this.projectSelectedDimension = JSON.parse(JSON.stringify(res));

      this.totalStores = Array();

      var storeCountIndex = 2;

      for (let k = 0; k < this.projectSelectedDimension.data.length; k++) {
        let obj = this.projectSelectedDimension.data[k];
        let xAxis = Object.keys(obj)[0];
        let yAxis = obj[Object.keys(obj)[0]][storeCountIndex];
        // console.log("x:", xAxis);
        // console.log("y:", yAxis);
        let objBarChart = { store: xAxis, storeCount: yAxis };
        this.totalStores.push(objBarChart);
      }
      this.initAxis() //put it here
    });

//    this.initAxis();
  }

【讨论】:

  • 然后接受答案。很高兴能提供帮助。
  • 嗨@dijolf,未定义错误的映射已经消失,现在在 initAxis() 函数中遇到“valueof 不是函数”的错误,请检查更新后的代码并在错误出现的地方添加注释跨度>
最近更新 更多