caveat: I am brand new to angular so I might have misunderstood how it is supposed to work.
I have an endpoint that I am hitting to get some data. I have created a model and I thought I could map the response straight into an array of models.
but it looks like it is ignoring the model completely I get my data back but it is the whole JSON data response. Not just the matching field from the model.
This is my service code
getFaults() {
return this.http.get<Fault[]>('<SITE>/api/faults')
}
This is my model
export interface Fault {
description: string
}
and this is the code I am calling in the page.ts
export class Tab1Page {
constructor(public faultsService: FaultsService) {}
faults: Fault[];
getFaults() {
console.log("click");
this.faultsService
.getFaults()
.subscribe((data: Fault[]) => console.log(data));
}
}
the output to console looks like this, I was expecting it would be an array of fault models, with just description mapped. Am I missing something?
There's nothing wrong with the code or behaviour. It does what's expected. The model is just typescript interface. What it does here is type-checking only:
getFaults() {
return this.http.get<Fault[]>('<SITE>/api/faults')
}
To get particular property description
from items of array data
, you need to loop over it and get these properties:
getFaults() {
console.log("click");
this.faultsService
.getFaults()
.subscribe((data: Fault[]) => {
const descriptions = data.map(obj => {
return { description: obj.description }
});
console.log(descriptions);
});
}