When we invoke our backend API, we retrieve some well defined data object, such as a Person
. By using TypeScript we can define the Type of such a data object and also provide this type to the Angular HttpClient
. As a consequence, our Http request gets “typed” and we get an instance of a Person
type.
In this example here, I am using here a people service, which internally uses the HTTP client to fetch some data which I directly print out here on the UI. As you can see, this is the structure of our data. However, if we work within here, our subscribe callback, we don't get any auto-completion from TypeScript, because it cannot infer the kind of data which we are retrieving.
The point here is, if we go into people service, we see that we get here an observable of type object, which is obviously not of type person. Let's quickly go here and define an interface person, which models our simple data structure.
What we can do now is to first of all return an observable of type person, but more interestingly, the new HTTP client introduced in Angular 4.3.1, which resides here in this Angular common HTTP package, has now here a type specifier where we can pass in the person interface which we just created.
Now in this way, if we go back to our app component, and we again try here to invoke that data object, we can see that TypeScript shows us that this of type person, and we can then access all the properties which are defined in this type.
Obviously, the data call itself still works as we would expect. This is a really powerful way of typing your response and catch errors early on in your process.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!