Angular Services

In the previous modules, we’ve covered almost every basic topic in Angular. Now we’re very much ready to move on to some advanced topics. In this article, you’ll be learning Services in angular.

Before knowing what a service is and how it can be used in your app, let’s understand why we need service.

Suppose we have an array of objects declared locally containing student details and a component where we want to display only student names. We can easily do that using the ngFor directive to display it into the view.

But, suppose we’ve another component where we’re required to display the complete student details.

Here the problem comes!!!

Either we have to copy-paste the array that contains the student details, which is not considered because we’re rewriting the same code over again rather than reusing. Or we need to find some other way. Yes, the other way is Service.

Services in Angular

Angular Service is basically a simple class with some special functionality. Service is used to serve data into multiple components and also used to interact with databases as well.

How to Create/Generate Angular Services?

Now, let’s see how to generate a service. First, open your window terminal and move to your app directory and type the below command.

ng generate service student

It will generate two files:

  • service.spec.ts
  • service.ts

NOTE: We can also use shortcuts, i.e., ng g s student, instead of writing full forms.


We hope this article has cleared your basic concepts on service, especially the need for service in our app and the command to generate service. In the upcoming articles, we’ll be learning how to use Service in our app.

Read Next: Angular Services Implementation

Leave a Reply

Your email address will not be published.