I have an API that returns an array of objects when queried with a GET. The response from the API has the form of:
[
{
"Ident": "Ag",
"Description": "Argent"
},
{
"Ident": "As",
"Description": "Arsenic"
}
]
In my app, I have an Element object with the following structure:
export class Element {
public ident: string;
public description: string;
constructor(ident: string, description: string) {
this.ident = ident;
this.description = description;
}
}
My app also has a service called mrcService with a function called getElements() that will send a GET request with HttpClient and returns an Observable array of objects Element:
getElements(): Observable<Element[]> {
return this.http.get<Element[]>(this.apiUrl)
.pipe(
catchError(this.handleError('getElements', []))
);
}
Finally, I have a component that subscribes to this service in ngOnInit() {}, it takes each element of the array returned by the API and push them into an array:
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
}
I now face two problems:
When pushing to my array, the observable properties must be referenced according to the nomenclature of the response by the API. I would like to use ident and * description* without capital letters like in my object definition instead of the capitalised letter from the API response.
I can't use this.elements[i] outside of .subscribe. When I do console.log(this.elements[i] it says undefined, but when I do console.log(this.elements) I can see the structure of the array.
console.log(this.elements[0])
outside of subscribe method, thethis.elements
arrays is not populated yet and that is why it's undefined. – Emin Laletovic