Welcome to part 5 of the Angular for Beginners series. We will be building up the application on the sample code referred to in the earlier parts of this series. So, it is recommended that you go through the earlier parts first. We have covered the following topics so far:
Services in Angular
In our demo, we have directly used hardcoded data in the employee.component.ts. We will now have a look at how we can use a service to get the data in Angular. Let’s create an employee service.
In the Angular CLI, type the following.
ng generate service employee
Notice the employee.service.ts file is created. It is also provided in ‘root‘ by default, which means the service will be available throughout the application. You can also modify this so that the service is available only for certain modules.
Do note how Angular decorates our service with @Injectable. This marks our service as a service that can be injected with something in the constructor. For example, in the next section when we learn how to use HttpClient to make requests, we will inject our service with an instance of the HttpClient in its constructor. If we don’t mark our service as @Injectable, we won’t be able to do inject anything in its constructor. So, when we mark our service as @Injectable, we are specifying that our service can be injected.
We will now create a getEmployees method in this service as below. Note that we have copied the hardcoded information from employee.component.ts into this service as below.
- getEmployees() : IEmployee[]{
- return[
- {
- "employeeId" : 1,
- "employeeName" : "Tuba",
- "projectId":100
- },
- {
- "employeeId" : 2,
- "employeeName" : "Atul",
- "projectId":101
- },
- {
- "employeeId" : 3,
- "employeeName" : "Theran",
- "projectId":101
- }]
Now, in our employee.component.ts file, we need to make some changes so as to fetch data from our service.
Note how we have imported the service and passed it to the constructor through dependency injection. In dependency injection, we passed an instance of the service. Then we defined employees as an array of ‘IEmployee’. We then assigned our employees array with the return array that we are getting from the employee service.
Our application should work as before.
Here, we have used a source of hardcoded values in our service. We could also use our service to fetch values from a Web API. This will be clear in the next part when we work with services using HTTP with Observables.
This concludes part 5 of the Angular for Beginners series. The official
Angular website also has some exciting material on services.
Let’s have a look at using HTTP with Observables for creating services in our next part. Stay tuned for that.
This article was originally published on my website
taagung.