【问题标题】:Can´t access to read properties in array with object无法使用对象访问读取数组中的属性
【发布时间】:2021-03-11 18:51:03
【问题描述】:

我正在使用 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
      }
    );

我收到这条消息:

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

对不起,我正在尝试用英文翻译我的问题。

问候

【问题讨论】:

    标签: javascript angular typescript ngrx


    【解决方案1】:

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

      ({ 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 对象。

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 2021-08-23
      • 2017-09-04
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      相关资源
      最近更新 更多