gpt4 book ai didi

javascript - Angular 2 |无法分配给数组,因为它是常量或只读属性

转载 作者:行者123 更新时间:2023-11-30 15:02:07 24 4
gpt4 key购买 nike

我正在尝试向返回对象数组的后端 api 发出获取请求。我正在使用以下代码:

small.component.ts(当调用 openDepositModal() 时,它从 auth.service.ts 调用函数 getUserInventory(),它向我的后端 api 发出获取请求,然后返回一个包含对象的数组。)

[...]

export class Item{
id: String;
name: String;
img: String;
value: String;
}

const items: Item[] = [];

[...]

openDepositModal(){
if(!items){
this.authService.getUserInventory().subscribe(data => {
items = data; <-- ERROR HERE
});
}
}

auth.service.ts

[...]

getUserInventory(){
let headers = new Headers();
this.loadToken();
headers.append('Authorization', 'JWT ' + this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/api/user/inventory', { headers: headers })
.map(res => res.json());
}

[...]

在 small.component.ts 内部,我试图将从服务获得的数据插入到“items”数组中。但是我收到错误“无法分配给数组,因为它是常量或只读属性”。有人可以修复我的代码吗?谢谢。 :-)

最佳答案

使用 let 而不是 const

例如让项目:Item[] = [];

const 声明类似于 let 声明,但正如其名称所暗示的那样,它们的值一旦被绑定(bind)就无法更改。换句话说,它们具有与 let 相同的作用域规则,但您不能重新分配给它们。

let vs. const (docs)

Given that we have two types of declarations with similar scopingsemantics, it’s natural to find ourselves asking which one to use.Like most broad questions, the answer is: it depends.

Applying the principle of least privilege, all declarations other thanthose you plan to modify should use const. The rationale is that if avariable didn’t need to get written to, others working on the samecodebase shouldn’t automatically be able to write to the object, andwill need to consider whether they really need to reassign to thevariable. Using const also makes code more predictable when reasoningabout flow of data.

On the other hand, let is not any longer to write out than var, andmany users will prefer its brevity. The majority of this handbook useslet declarations in that interest.

关于javascript - Angular 2 |无法分配给数组,因为它是常量或只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com