The Quiz client-side interface

The first thing we need to do is to add the Quiz interface to our Angular-enabled client. Wait a minute, should we really do that? Can’t we just use the raw JSON data sent by the QuizController’s Get and GetLatest methods defined earlier, consuming them as anonymous JavaScript objects?

Theoretically speaking, we can, just as much as we can output raw JSON from the Controllers instead of creating all the ViewModel classes, like we did instead. In a well-written app, though, we should always resist the temptation to handle raw JSON data and/or to use anonymous objects for a number of good reasons:

  • We have chosen TypeScript over JavaScript because we want to work with type definitions. Anonymous objects and properties are the exact opposite; they lead to the JavaScript way of doing things, which is something we wanted to avoid in the first place.
  • Anonymous objects (and their properties) are not easy to validate: we don’t want our data items to be error prone or forced to deal with missing properties or anything like that.
  • Anonymous objects are hardly reusable, and won’t benefit from many Angular handy features--such as the object mapping--that will require our objects to be actual instances of an interface and/or a type.

The first two arguments are very important, especially if we’re aiming for a production-ready application; no matter how easy our development task might seem at first, we should never think that we can afford losing that level of control over our application’s source code.

The third reason is also crucial as long as we want to use Angular to its full extent. If that’s the case, using an undefined array of properties such as raw JSON data is basically out of the question; we will use a TypeScript interface, as it is the most lightweight way to work with structured JSON data in a strongly-typed fashion. More specifically, we'll add a dedicated Quiz interface to properly map our JSON-serialized QuizViewModel server-side class.

From Solution Explorer, right-click on the /ClientApp/app/ folder and create a new /interfaces/ subfolder, and then right-click on it and add a new TypeScript file in there; call it quiz.ts and fill its content with this source code:

interface Quiz {
Id: number;
Title: string;
Description: string;
Text: string;
}

Note that we’re not (yet) mapping all the properties present in the QuizViewModel class; as a general rule of thumb, we’ll be keeping these classes as lightweight as possible, defining only what we know we will use for the time being. We can always add more properties later, as soon as we need them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.56.29