Angular 10 Tutorial - Service

In this tutorial, we will learn about Services in Angular 10. An Angular service is a stateless object that provides some very useful functions. These functions can be invoked from any component of Angular, such as Controllers, Directives, etc. This helps in dividing the web application into small, different logical units that can be reused.

Using Services in Angular 10

Now, let's see how we can use services in Angular 10. First, let's create a service. For that, switch to the command prompt and run the command:


ng g service g user

Alright, the service has been created. Now, switch to the project and inside the app directory. You can see the user.service.ts file. Inside this file, create a function:


getAllUsers()
{
return [
{name:'Alice',email:'alice@gmail.com',phone:'1234567890'},
{name:'Andrew',email:'andrew@gmail.com',phone:'1234567891'},
{name:'Mike',email:'mike@gmail.com',phone:'1234567892'},
{name:'Shopie',email:'shopie@gmail.com',phone:'1234567893'},
{name:'Steve',email:'steve@gmail.com',phone:'1234567894'}
]
}

Now, save this service file and let's use this service in the component. For that, just go to the app.component.ts file and import the service first:


import {UsersService} from './users.service';

Create a property and inside the constructor, just write as follows:


user = null;
constructor(private user:UsersService){
this.users = this.user.getAllUsers();
}

Now, let's print the user on HTML. So, just open the app.component.html file and write the following code:


<h2>All Users</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of Users">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
</tr>
</tbody>
</table>

Alright, all done! Let's check this. So, switch to the browser and you can see all the users. So, in this way, you can use services in Angular 10.