Join Alexander Zanfir for an in-depth discussion in this video Angular service, part of Building Applications with Angular, ASP.NET Core, and Entity Framework Core.
- [Instructor] Let's begin by creating an Angular service that will allow us to post new questions. Back in our editor, we'll create a new file in our app directory. We'll call it api.service.ts. And the first thing we'll do inside is create the class and export it. And just like components, we'll need to add a decorator. But unlike components, we'll need a different type of decorator called Injectable.
We'll get access to that by importing Injectable from @angular core. And now, let's create the decorator. There's no properties to set for now inside our Injectable, so it just designates this API service class as an Injectable service. From our question component, we'll need to post a new question, so we'll need to have a postQuestion function inside our service.
And of course, that will take a question as the value. Inside our postQuestion function, we'll need to send an HTTP request to our backend. To do that, we'll need to work with the HTTP module from Angular. So, let's go to the top and import that. And that's from angular slash common slash http. And this is the new and updated HTTP module from Angular four and up.
Next, let's inject it with a constructor. So, I'll go to the top of our class and create a constructor, and then we'll inject HTTP client and save it as a reference. Now, inside our postQuestion function on line 10, we'll call this.http.post and we'll pass in the URL once we get it, and then we'll pass in the question. Next, in order to execute the HTTP post and get the response, we'll need to use dot subscribe on the end, and we'll take in our response and using an arrow function, we'll simply console log the response for now.
We don't yet have an HTTP post backend endpoint, so we'll need to create that in our ASP.NET core project. So for now, just double check that your app is not giving you any errors, and then let's focus on our backend next.
- Creating and configuring the Angular project
- Creating forms with Angular
- Creating get and post routes in an ASP.NET Core controller
- Updating Angular service to post to API
- Persistence with Entity Framework
- Displaying and editing data in Angular with ASP.NET Core
- Navigating to different views in Angular
- Associations between entities with Angular and Entity Framework
- Setting up Identity Framework