How to create a service in Angular 10?

In this blog, we will see that how can we create or add a new service in any component of angular 10 using CLI. Here we will create a service name as ‘Post’ and will add it to the app component. We will explain you step by step as follows:how-to-create-a-service-in-angular-10

First, you need to create a new project in angular 10. If you want to see that how to create a new app or new project with Angular 10, please follow our blog How to create a new app or new project with angular 10? how-to-create-a-service-in-angular-10

Now we are going to create a simple service named ‘post’ by CLI command. In this service file, we will create getPosts() and it will return an array.how-to-create-a-service-in-angular-10

We have just need to run the following command to create the service here:how-to-create-a-service-in-angular-10

ng g service Post

We can see that there is a service file post.service.ts has created as below :

The post.service.ts file is generated as follows:

Add Service in the component

Now, we need to import the service into the app component file as following code :

View File to show on the front end

Now, we add our array[] data to the view to display our posts on the app as follows:

app.component.html file

Now you can run your application by the command ng serve

You can see the layout as below:

Finally, we can see above that we have successfully created our service in the angular app.

I hope you will follow the above steps and create your Angular 10 service.

how-to-create-a-service-in-angular-10

So, thanks for following this blog, and if you need any help please leave your queries in the comment box, we will be happy to help you.how-to-create-a-service-in-angular-10 how-to-create-a-service-in-angular-10 how-to-create-a-service-in-angular-10how-to-create-a-service-in-angular-10how-to-create-a-service-in-angular-10 how-to-create-a-service-in-angular-10