Search code examples
angulartypescriptangular2-services

Angular - enforcing a model format in a returned JSON array


While using Angular I have the following model:

export interface MyModel {
    id: number;
    content: string;
}

In a service I make a request for JSON data that has the attributes of MyModel. Something like this:

function getMyModel() {
    return this.http
       .post('http://www.somewhere.com/getOneModel')
       .map(result => <MyModel> result.json())
       .catch(this.handleError);
}

The returned JSON is something like this:

{ id: 1, content: "Stuff" }

In getMyModel() you'll see that while I map() the results I make sure that the JSON conforms to MyModel by doing this: <MyModel> result.json().

Everything is working fine to this point.

Now I want to return an array of models and confirm all of them conform to MyModel.

function getLotsOfModels() {
    return this.http
       .post('http://www.somewhere.com/getLotsOfModels')
       .map(result => result.json())
       .catch(this.handleError);
}

The returned JSON is something like this:

{[
    { id: 1, content: "Stuff" },
    { id: 2, content: "More stuff" }
]}

In this case map() cannot confirm the JSON array elements agree with MyModel since the result is an array. How can I check that the results are correct?


Solution

  • You can cast them to MyModel[].

    function getLotsOfModels() {
        return this.http
         .post('http://www.somewhere.com/getLotsOfModels')
         .map(result => <MyModel[]> result.json())
         .catch(this.handleError);
    }
    

    Typescript won't do any structural check, so casting this can only fail at runtime. If you have any methods on MyModel. The Json won't have them, and you'll run into problems, when you want to evoke a method.

    For example, after you've obtained your model:

    myModel.myMethod();
    

    This will throw an error at runtime, since the underlying JSON, doesn't have the function defined and the compiler can't catch it because of the cast.