【发布时间】:2017-09-23 03:25:56
【问题描述】:
我正在尝试向我的后端 api 发出一个 get 请求,该请求返回一个对象数组。我正在使用以下代码:
small.component.ts (调用 openDepositModal() 时,它从 auth.service.ts 调用函数 getUserInventory(),该函数向我的后端 api 发出 get 请求,然后返回一个包含对象的数组。)
[...]
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”数组中。但我收到错误“无法分配给数组,因为它是常量或只读属性”。有人可以修复我的代码吗?谢谢。 :-)
【问题讨论】:
标签: javascript angular typescript