从不同的类导入时无法在模板中使用对象的属性

问题描述 投票:0回答:1

我是 Angular 新手,我面临的问题是 Angular16 在外部类中定义时不显示对象的属性。看看下面的插图。

我通过以下方式定义了一个类。我使用此类来存储从后端接收的数据。这些值在其他组件中重用。

export class StaticClass {
    static dict:{[key: string]: Array<object> } = {
        1: [],
        2: [
            { id: 1, text: "Hello" },
        ],
        3: [],
}}

然后我导入此类以使用存储的值。

import { Component } from '@angular/core';
import { StaticClass } from 'src/app/utils/calendarEvents';

@Component({ ..<omitted>.. })
export class SampleViewComponent {
    staticClass = StaticClass;
    temp = [{ id: 1, text: "Hello" }]


   constructor(){
        console.log(this.staticClass.dict[2])
        console.log(this.temp)
    }
}

在这里,两个控制台输出显示相同的内容。 但是,当我尝试显示 staticClass 中的值时,TS 抛出错误。

<div *ngFor="let i of this.staticClass.dict[2]">
    {{ i.id }}
</div>

类型“object”上不存在属性“id”。ngtsc(2339)

但是使用 temp 时效果很好。

<div *ngFor="let i of this.temp">
    {{ i.id }}
</div>

问题:

  1. 如何纠正上述问题? tempstaticClass.dict[2]
  2. 有什么不同
  3. 有没有更好的方法来存储我从后端收到的值?由于这些都是临时的并且始终在变化,因此我不想使用浏览器本地存储。
angular angular16
1个回答
0
投票

数值差异:

  1. 中的

    StaticClass
    :定义为
    Array<object>
    类型。

  2. 对于

    temp
    变量:定义为
    { id: number; text: string; }[]

尽管有共同点,我们都知道它们都是对象数组,但编译器对它们的处理方式有所不同。

object
实现/扩展
Object
接口。供您参考:“任何”与“对象”

如果您知道对象的结构并且它是一致的(相同的结构应用于所有对象),您可以将类型定义为:

export class StaticClass {
  static dict: { [key: string]: Array<{id: number; text: string}> } = {
    1: [],
    2: [{ id: 1, text: 'Hello' }],
    3: [],
  };
}

或者您可以使用

any
以便编译器跳过类型检查。

export class StaticClass {
  static dict: { [key: string]: Array<any> } = {
    1: [],
    2: [{ id: 1, text: 'Hello' }],
    3: [],
  };
}

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.