首页 > 解决方案 > 无法使用对象访问读取数组中的属性

问题描述

我正在使用 angular+ngrx,但我遇到了一个问题,这是控制台中的输出

{status: true, rows: 1, data: Array(1)}
data: Array(1)
0: {id: "Q", description: "QQQQQ", is_active: true, created_at: "2021-02-05T01:24:21.594Z", updated_at: "2021-02-05T01:24:21.594Z"}
length: 1
__proto__: Array(0)
rows: 1
status: true
__proto__: Object

但是,我无法访问像 id 这样的数组内部对象的属性。我定义了一个这样的接口:

export interface TipoDocumentoResult {
    status: boolean;
    rows: number;
    data: TipoDocumento
}

TipoDocumento 是一个类:

export class TipoDocumento {
    constructor(
        public id: string,
        public description: string,
        public is_active: boolean,
        public created_at: Date,
        public updated_at: Date,
    ) { }
}

这是我的 ngOnInit:

this.store.pipe(
      select('tipoDocumentoGetOne'),
      filter(({ loading, loaded }) => loading === false && loaded === true),     
    ).subscribe(
      ({ data }) => {
        this._result = data
        this._data = this._result?.data
        console.log(this._result)
        console.log(this._data[0]) // Here, i get error message
      }
    );

我收到这条消息:

元素隐式具有“任何”类型,因为类型“0”的表达式不能用于索引类型“TipoDocumento”。类型“TipoDocumento”上不存在属性“0”

抱歉,我正在尝试用英语翻译我的问题。

问候

标签: javascriptangulartypescriptngrx

解决方案


看起来你已经在你的订阅中解构你的对象:

  ({ data }) => { // variable 'data' is already of type TipoDocumento 

你基本上是在说:有一个对象来了,它有一个“数据”字段,我只对那个特定的字段感兴趣。如果您在订阅中更改“数据”的名称,您实际上应该得到一个编译错误。

我认为你需要的实际上是这样的:

this.store.pipe(
      select('tipoDocumentoGetOne'),
      filter(({ loading, loaded }) => loading === false && loaded === true),     
    ).subscribe(
     result => {
        this._result = result 
        this._data = this._result?.data
        console.log(this._result)
        console.log(this._data[0]) // Here, i get error message
      }
    );

NRGX 的旁注:在 NGRX 存储中使用类(在您的情况下为 TipoDocumento)是有风险的,因为难以保证不变性,并且诸如 NGRX 实体之类的帮助框架实际上将类分解为普通的 javascript 对象。


推荐阅读