0

In an Angular5 app, I'm making an HTTP request to a data layer that's shared by several apps.

The end-point returns an array of long and complex JSON objects.

Is it a best practice to take the return from the data service more or less "as is" as work directly with it?

Or should I turn it into an array of objects that conform to a class that I defined as a model?

I come from a Java background so building objects from a class feel right. Are there benefits to doing this in Angular, or any JS context, or would it be a waste of time?

1
  • 2
    DTOs in typescript are replaced by interfaces. The rule of thumb is: if you want to have an structure that stores data and defines behavior, use a class. If you only want to store data, use an interface. This is partially explained in the http client guide angular.io/guide/http#type-checking-the-response Commented May 1, 2018 at 22:04

1 Answer 1

1

Making a model corresponding to the data you require at the front end makes sense. This is because you will have control over what all data goes into the object, you will also have a consolidated object over which you will be able to pinpoint what all data is contained. Also, you will not carry extra data to the next layer.

You could simply write a class or an interface and then import it where you get your data and make an object of that class/interface and populate data into it.

eg -->

//this is where you declare what all fields would be present

export Class Student {
    id: number;
    name: string;
}

//this is where you consume it
let students: Student[] = [];

//iterate over students and push the details to students array.
let student = new Student({
    id : currentIteratedStudent.id,
    name: currentIteratedStudent.name
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.