我正在尝试将用户输入存储在模型中,如果我可以在对象中嵌套属性,并且在我的组件中使用它们,那么这将更好地组织。
我的尝试模型:
export class carConfig {
make: string;
model: string;
colors: Colors;
}
class colorDetail {
id: number;
name: string;
}
export class Colors {
exterior: colorDetail;
interior: colorDetail;
interiorTrim: colorDetail;
roof: colorDetail;
}
使用以下代码:
setSelectedColor(category: string, colorID: number, colorName: string): void {
switch (category) {
case 'Exterior':
this.car.colors.exterior.id = colorID;
this.car.colors.exterior.name = colorName;
console.log('1');
break;
case 'Interior':
this.car.colors.interior.id = colorID;
this.car.colors.interior.name = colorName;
console.log('2');
break;
case 'Interior Trim':
this.car.colors.interiorTrim.id = colorID;
this.car.colors.interiorTrim.name = colorName;
console.log('3');
break;
case 'Roof':
this.car.colors.roof.id = colorID;
this.car.colors.roof.name = colorName;
console.log('4');
break;
default:
break;
}
}
我收到以下错误:
Property 'Exterior' does not exist on type 'Object'.)
如何创建模型,该模型表示我的组件要使用的对象?
答案 0 :(得分:2)
您应该使用角度模型绑定来完成所有这些操作,但在原始代码示例的范围内,以下结构可以很好地工作
<强> car.ts 强>
export interface Car {
make: string;
model: string;
colors: Colors;
}
export interface Color {
id: number;
name: string;
}
export interface Colors {
exterior: Color;
interior: Color;
interiorTrim: Color;
roof: Color;
}
export const ColorSelectionToPropertyMap = Object.freeze({
'Roof': 'roof',
'Exterior': 'exterior',
'Interior': 'interior',
'Interior Trim': 'interiorTrim'
});
export type ColorSelectionToPropertyMap = typeof ColorSelectionToPropertyMap;
export function createCar(make?: string, model?: string): Car {
return {
make,
model,
colors: {} as Colors
};
}
使用代码
import {
createCar,
ColorSelectionToPropertyMap
} from './car';
export class CartComponent {
car = createCar();
setSelectedColor(
category: keyof ColorSelectionToPropertyMap,
id: number,
name: string
) {
const propertyName = ColorOptions[category];
this.car.colors[propretyName] = {
name,
id
};
}
}