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.




Amit MohantyPosted Jun 28, 2019, 1:42 AM
Nice article !!!