[英]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我正在使用 angular+ngrx,但我遇到了一个问题,这是控制台中的 output
{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.但是,我无法访问像 id 这样的数组内部的 object 的属性。 I defined a interface like this:
我定义了一个这样的接口:
export interface TipoDocumentoResult {
status: boolean;
rows: number;
data: TipoDocumento
}
and TipoDocumento is a class: TipoDocumento 是 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:这是我的 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'.元素隐式具有“任何”类型,因为类型“0”的表达式不能用于索引类型“TipoDocumento”。 Property '0' does not exist on type 'TipoDocumento'
类型“TipoDocumento”上不存在属性“0”
Sorry, i'm trying to translate in english my problem.抱歉,我正在尝试用英语翻译我的问题。
Regards问候
Looks like you are already destructuring your object in your subscribe:看起来您已经在订阅中解构 object:
({ 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.你基本上是在说:有一个 object 来了,它有一个“数据”字段,我只对那个特定的字段感兴趣。 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. NRGX 的旁注:在 NGRX 存储中使用类(在您的情况下为 TipoDocumento)是有风险的,因为难以保证不变性,并且诸如 NGRX 实体之类的辅助框架实际上将 class 分解为普通的 javascript ZA8ZCFDE68911B4B666AC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.