2017-05-09 51 views
2

我正在尝试创建一个模拟应用程序,将一些数据显示为按钮列表。我实施了一切,但现在我正面临着这个问题。我初始化了一个数组和另一个类的数据。数组中的泛型?

-items.ts 

    export class ItemPage { 

    items: Item[] = []; 

    constructor() { 

    this.items.push(
     new Item(1, 'Apple', 'Green', 6, true)); 
    this.items.push(
     new Item(2, 'Banana', 'Yellow', 15, false)); 
    } 

和数据类看起来像这样

-item.ts 

export class Item { 
    constructor(
    id: number, 
    fruit: string, 
    color: string, 
    quantity: number, 
    onStock: boolean, 
) { } 
} 

我现在面临一个问题,items: Item[] = [];当我运行ionic serve。它说Generic type 'Item' requires 2 type argument(s)type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T
我试图解决它,但它没有帮助,有没有人有任何想法如何解决这个问题?

谢谢

+3

看起来'Item'是Ionic中的保留字/类。尝试将您的“Item”更改为不同的名称。 –

+0

我试过你的建议,但我仍然有同样的问题 – Maged

+0

项目 []也许? –

回答

0

我没有完全设法重现问题,而是结束了两个空的对象。错误看来你是不是设置在类的属性public,所以改变你的类:

export class Item { 
    constructor(
    public id: number, 
    public fruit: string, 
    public color: string, 
    public quantity: number, 
    public onStock: boolean, 
) { } 
} 

似乎很好地工作:Plunker

我强烈建议你应该使用接口,如果你不需要在类或其他原因的功能。所以我会说你做接口:

export interface Item { 
    id: number; 
    fruit: string; 
    color: string; 
    quantity: number; 
    onStock: boolean; 
} 

constructor(private navController: NavController) { 
    this.items.push({id:1, fruit:'Apple', color:'Green', quantity:6, onStock:true}); 
    this.items.push({id:2, fruit: 'Banana',color:'Yellow',quantity:15,onStock:false}) 
} 

希望这有助于!

+0

嗨,这段代码是怎么回事?它有帮助吗? :) – Alex

+0

嘿,是的,它的工作表示感谢。 如果我想在另一个班级使用军队,我该怎么做? 我试过这个: 'export class Stats { public stat:number; 构造函数(items:Item []){ this.stat = items.length; } }' 但它不停地给我同样的错误'通用型“项目”需要2个类型参数(S)' – Maged

+0

由于该解决您的问题,你会笑纳的答案:)但是,回到你的问题。 ..什么是*军队*这是什么类'Stats'是一个新的类或什么? – Alex