Angular class 实例正在生产构建中提供对象实例

Angular class instance is giving object instance in production build

我正在使用 Angular 8

在应用程序中,我有一个对象数组来相应地在 HTML

中呈现数据
public components = [
  {
    type: "button",
    data: {
      label: "Click here"
    }
  },
  {
    type: "description_box",
    data: {
      content: "Enter description"
    }
  }
]

现在有两个按钮添加按钮添加描述框当用户点击按钮时,请求的对象被推送到components 数组的处理方式类似于

onClick(component: string) {
  switch(component) {
    case 'button': data = new Button(); break;
    case 'description_box': data = new DescriptionBox(); break;
  }

  this.components.push({
    type: this.getTypeFromData(data),
    data: data
}

/**
 * spit class constructor name in lowercase underscored
 * Ex: DescriptionBox -> description_box
 */
private getTypeFromData(data) {
  const className = data.constructor.name.split(/(?=[A-Z])/);

  let componentType = '';
  for (const name of className) {
    componentType += name + '_';
  }

  return componentType.toLowerCase().slice(0, -1);
}

两个class很像

components.ts

export class Button {
  label: string;
  color: {
    label: string;
    button: string;
    border: string;
  };
  link: string;
}

export class DescriptionBox {
  text = 'New Title';
}

这在本地开发中工作正常,但在生产构建中没有按预期工作。

在生产构建中,class 实例给出 o 对象而不是 class 实例。

发生这种情况是因为您的 类 被缩小了,所以需要更少的 space。而不是检查 constructor.name 你可以用 data instanceof DescriptionBox 来检查它。