Angular 6 HttpClient对myObject的JSON响应
我有一个API,当使用GET查询时,它返回一个对象数组。API的响应形式为:Angular 6 HttpClient对myObject的JSON响应,angular,angular6,Angular,Angular6,我有一个API,当使用GET查询时,它返回一个对象数组。API的响应形式为: [ { "Ident": "Ag", "Description": "Argent" }, { "Ident": "As", "Description": "Arsenic" } ] 在我的应用程序中,我有一个具有以下结构的元素对象: export class Element { public ident: str
[
{
"Ident": "Ag",
"Description": "Argent"
},
{
"Ident": "As",
"Description": "Arsenic"
}
]
在我的应用程序中,我有一个具有以下结构的元素对象:
export class Element {
public ident: string;
public description: string;
constructor(ident: string, description: string) {
this.ident = ident;
this.description = description;
}
}
我的应用程序还有一个名为mrcService的服务,该服务带有一个名为getElements()的函数,该函数将通过HttpClient发送GET请求,并返回一个可观察的对象数组元素:
getElements():可观察{
返回this.http.get(this.apirl)
.烟斗(
catchError(this.handleError('getElements',[]))
);
}
最后,我在ngOnInit(){}中有一个订阅此服务的组件,它接受API返回的数组的每个元素,并将它们推送到一个数组中:
elements: Array<Element> = [];
ngOnInit() {
this.mrcService.getElements()
.subscribe(res => {
res.forEach(item => {
this.elements.push(new Element(item.Ident, item.Description));
});
console.log(this.elements[0]); // returns the object at the index
});
console.log(this.elements[0]); // returns undefined
}
元素:数组=[];
恩戈尼尼特(){
this.mrcService.getElements()
.订阅(res=>{
res.forEach(项目=>{
此.elements.push(新元素(item.Ident,item.Description));
});
console.log(this.elements[0]);//返回索引处的对象
});
console.log(this.elements[0]);//返回未定义的
}
我现在面临两个问题:
- 当推送到我的数组时,必须根据API响应的名称引用可观察属性。我想使用ident和*description*,而不是像在我的对象定义中那样使用大写字母,而不是API响应中的大写字母
- 我无法在.subscribe之外使用此.elements[I]。当我执行console.log(this.elements[I]时,它表示未定义,但当我执行console.log(this.elements)时,我可以看到数组的结构
请记住,观察对象是异步的,因此在订阅之外执行console.log时,您的http请求尚未完成。1.不确定后端的服务代码,但如果不是自动的,则需要设置在返回结果时将属性名称解析为camelCase。2.在
c的特定情况下onsole.log(this.elements[0])
在subscribe方法之外,this.elements
数组尚未填充,这就是它未定义的原因。1.不确定后端的服务代码,但如果不是自动的,则需要设置在返回结果时将属性名称解析为camelCase。2.在console.log(this.elements)的特定情况下[0])
在subscribe方法之外,this.elements
数组尚未填充,这就是它未定义的原因。我完全没有考虑subscribe方法的异步性。我完全没有考虑subscribe方法的异步性。
elements: Array<Element> = [];
ngOnInit() {
this.mrcService.getElements()
.subscribe(res => {
res.forEach(item => {
this.elements.push(new Element(item.Ident, item.Description));
});
console.log(this.elements[0]); // returns the object at the index
});
console.log(this.elements[0]); // returns undefined
}