简体   繁体   中英

Can´t access to read properties in array with object

i'm using angular+ngrx, but i get a problem, this is output in console

{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

but, i can't access to the properties of the object inside of array like id. I defined a interface like this:

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

and TipoDocumento is a class:

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

This is my 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
      }
    );

i get this message:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'TipoDocumento'. Property '0' does not exist on type 'TipoDocumento'

Sorry, i'm trying to translate in english my problem.

Regards

Looks like you are already destructuring your object in your subscribe:

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

You are basically saying: There is an object coming which has a 'data' field and I'm only interested in that particular field. If you change the name of 'data' in your subscribe, you should actually get an Compile Error.

I think what you need is actually this:

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
      }
    );

And a sidenote to NRGX: Using classes (in your case TipoDocumento) in NGRX Store is risky, since immutability is hard to assure and Helper Frameworks such as NGRX Entity actually break the class into a plain javascript object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM