我开始使用Angular并遇到错误 .
... / mocks.ts(9,4):输入'{“id”:number; “name”:string; “description”:字符串; “inStock”:数字; “价格”:数量; “featu ...”不能分配给'CarPart []类型 . 对象文字只能指定已知属性,'carPart'类型中不存在'“featured”' .
我的代码:
汽车part.ts
export class CarPart {
id: number;
name: string;
description: string;
inStock: number;
price: number;
featured: boolean;
}
mock.ts
import { CarPart } from './car-part';
export const CARPARTS: CarPart[] = [{
"id": 1,
"name": "Super Tires",
"description": "These tires are the very best",
"inStock": 5,
"price": 299.99,
"featured": false //Line 9
},
{
"id": 2,
"name": "Reinforced Shocks",
"description": "Shocks made of kryptonite",
"inStock": 4,
"price": 500.50,
"featured": false
},
{
"id": 3,
"name": "Padded Seats",
"description": "Super soft seats for a smooth ride",
"inStock": 0,
"price": 333.33,
"featured": true
}];
汽车parts.component.ts
import { Component, OnInit } from '@angular/core';
import { CarPart } from './car-part';
import { CARPARTS } from './mock';
@Component({
selector: 'car-parts',
templateUrl: './car-parts.component.html',
styleUrls: ['./car-parts.component.css']
})
export class CarPartsComponent implements OnInit {
constructor() { }
carParts: CarPart[];
totalCarParts(){
let sum = 0;
for(let carPart of this.carParts){
sum += carPart.inStock;
}
return sum;
}
ngOnInit() {
this.carParts = CARPARTS;
}
}
当我从mock.ts和car-part.ts中删除“精选”时它很好,没有错误 . 如果我添加它或任何其他名称或类型,它将无法正常工作......有人能解释一下吗?
1 回答
我重新启动了Angular CLI服务器(Ctrl C> ng serve) . 编译没有问题......
证据表明“你试过把它关掉再打开”仍然是有意义的 . 感谢时间看Tim和Max的问题