While working with Angular, I have a model defined as follows:
export interface MyModel {
id: number;
content: string;
}
In one of my services, I fetch JSON data that matches the attributes of MyModel. Here's an example:
function getMyModel() {
return this.http
.post('http://www.somewhere.com/getOneModel')
.map(result => <MyModel> result.json())
.catch(this.handleError);
}
The JSON response looks something like this:
{ id: 1, content: "Stuff" }
In the getMyModel()
function, I ensure that the JSON structure aligns with MyModel by using <MyModel> result.json()
within the map() method.
So far, everything is functioning as expected.
Now, I want to retrieve an array of models and validate that they all adhere to MyModel.
function getLotsOfModels() {
return this.http
.post('http://www.somewhere.com/getLotsOfModels')
.map(result => result.json())
.catch(this.handleError);
}
The returned JSON looks like this:
{[
{ id: 1, content: "Stuff" },
{ id: 2, content: "More stuff" }
]}
In this scenario, using map() alone cannot verify if each element in the JSON array complies with MyModel since it's an array. How can I ensure that all results are in line with the MyModel interface?