尝试在ngOnInit
函数中填充用于测试目的的Product数据类型的数组,如下所示:
import { Component, OnInit } from '@angular/core';
import {IProduct} from "../product-list/product";
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-detiail',
templateUrl: './product-detiail.component.html',
styleUrls: ['./product-detiail.component.css']
})
export class ProductDetiailComponent implements OnInit {
pageTitle = "Product Detail";
product: IProduct[];
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
let id = +this.route.snapshot.paramMap.get('id');
this.pageTitle = `:${id}`;
this.product = {
"productId": 10,
"productName": "Saw",
"productCode": "TBX-0022",
"releaseDate": "May 15, 2016",
"description": "15-inch steel blade hand saw",
"price": 11.55,
"starRating": 3.7,
"imageUrl": "http://openclipart.org/image/300px/svg_to_png/27070/egore911_saw.png"
};
}
}
我有一个在接口中指定的IProduct
数据类型,可以在这里看到:
export interface IProduct{
productId: number;
productName: string;
productCode: string;
releaseDate: string;
price: number;
description: string;
starRating: number;
imageUrl: string;
}
可以看出,接口和ngOnInit
中给出的数据匹配,但是在代码编译时遇到了以下错误:
ERROR in src/app/components/product-detail/product-detiail.component.ts(24,7): error TS2322: Type '{ "productId": number; "productName": string; "productCode": string; "releaseDate": string; "description": string; "price": number; "starRating": number; "imageUrl": string; }' is not assignable to type 'IProduct[]'.
Object literal may only specify known properties, and '"productId"' does not exist in type 'IProduct[]'.
我对为什么会发生这种情况感到非常困惑。我想念什么?任何帮助将不胜感激,谢谢。
答案 0 :(得分:2)
将product: IProduct[]
更改为product: IProduct
您已将product
定义为IProduct-> IProduct[]
的数组,并为其分配了类型IProduct
的单个对象。因此,您收到此错误。
要分配类型为IProduct[]
的产品,请执行以下操作:
product: IProduct[] = [
{
"productId": 10,
"productName": "Saw",
"productCode": "TBX-0022",
"releaseDate": "May 15, 2016",
"description": "15-inch steel blade hand saw",
"price": 11.55,
"starRating": 3.7,
"imageUrl": "http://openclipart.org/image/300px/svg_to_png/27070/egore911_saw.png"
}
]
或
product : IProduct[]= []
product.push(
{
"productId": 10,
"productName": "Saw",
"productCode": "TBX-0022",
"releaseDate": "May 15, 2016",
"description": "15-inch steel blade hand saw",
"price": 11.55,
"starRating": 3.7,
"imageUrl": "http://openclipart.org/image/300px/svg_to_png/27070/egore911_saw.png"
}
)