【问题标题】:How to iterate in a union type array in angular template如何在角度模板中迭代联合类型数组
【发布时间】:2021-08-17 18:01:28
【问题描述】:

我是 Angular 新手,开始使用第 12 版,但我陷入了困境。在哪里 我想在模板中迭代我的联合数组,但它给了我错误。

错误: 输入'IBasketItem[] | IOrderItem[]' 不可分配给类型 'NgIterable'。

这是我要迭代的组件中的联合数组。

@Input() items: IBasketItem[] | IOrderItem[] = [];

这是模板代码

<tr *ngFor="let item of items" class="border-0">

它在 ' of ' 关键字下给了我一条红线,上面提到了错误

这是 IBasketItem 接口

export interface IBasketItem {
id: number;
productName: string;
price: number;
quantity: number;
pictureUrl: string;
brand: string;
type: string;

}

这是 IOrderItem 接口

export interface IOrderItem {
productId: number;
productName: string;
pictureUrl: string;
price: number;
quantity: number;

}

如果有人提出解决方案,我将不胜感激。

【问题讨论】:

    标签: angular typescript ngfor


    【解决方案1】:

    像这样声明类型的数组 @Input() items: [IBasketItem | IOrderItem] = [];

    那么这是可迭代的。

    或者这样

    @Input() items: Array&lt;IBasketItem | IOrderItem&gt; = [];

    【讨论】:

    • 感谢您的宝贵时间,但您的解决方案对我不起作用。当我应用您的解决方案时,它无法在我的界面中找到属性。
    【解决方案2】:

    虽然@Hitech 的回答可能有效,但您尝试做的事情有点粗略。 您必须检查是否有可用的“品牌”或“类型”属性,然后显示它们或对 orderItem 或篮子项目有不同的逻辑。

    我建议您对它们都有一个通用接口,然后遍历该数组:

    export interface IItem {
        id: number;
        productName: string;
        price: number;
        quantity: number;
        pictureUrl: string;
    }
    
    export interface IOrderItem extends IItem {
        productId: number; // might be the same with the id from the base class, depending on your logic
    }
    
    export interface IBasketItem extends IItem {
        brand: string;
        type: string;
    }
    
    @Input() items: IItem[] = [];
    

    或者为此设置两个单独的数组,并为每个数组设置一个 for 循环。

    @Input() basketItems: IBasketItem [] = [];
    @Input() odredItems: IOrderItem [] = [];
    

    【讨论】:

    • @qbBlaze 感谢您的努力,但遗憾的是您的第一个解决方案对我不起作用,对于第二个解决方案,我不能使用单独的数组。
    【解决方案3】:

    Angular 检查应用程序代码中模板中的表达式和绑定。尝试在tsconfig.json 文件中设置"strictTemplates": false 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-09
      • 2021-11-16
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      相关资源
      最近更新 更多