Hello guys! This is the time for another Angular tutorial.. Have you read my previous Angular articles? Not yet? Click the below link to read all of them.. Reading them is recommended as a prerequisite for this articles!
Angular article series

What are Angular Services?

Services allow us to extract the common functionalities in the components and include them in separate classes. This avoids code redundancy! We don't have to write the same code again an again when we use services. It's reusable. The only thing we have to do is injecting the services in all the components. Main benefits:
  • Make the code base modular
  • Support for code separation
  • Make easy to maintain applications 

Service also a class in Angular Class with a injectable decorator. Usually data driven logic and methods are included in these service classes. Whenever we want to provide s service to a component or any other place, we have to use a process called Dependency Injection.
The process in brief...
What is our goal?
We are going to display an array using a service.. This array contains the data we provides to a component. Let's start!
I think you have the project that we previously created during this article series.. If you don't have it, create new one..It's not a matter!

Go into project folder using cmd and create a new component called user-list.

3 main steps to use Services

1. Define a service class
2. Register the service with Injector
3. Declare it as a dependency where we want

Step 1 - Define the service

Open cmd and create a new service class named as user-service.
ng g s user

Now you will have a service class called user.service.ts. There will be another spec.ts file..Do not consider it. Open user-service TypeScript file in your editor. This service is called as UserService by Angular naming conventions. 
We have to define the array (data) in the class. To retrieve these data I define a method called getUsers. See the code below.

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {
  constructor() { }

  getUsers() {
    return [
      {
        'id': 1,
        'name': 'salitha',
        'job': 'Web Developer'
      },
      {
        'id': 2,
        'name': 'chathuranga',
        'job': 'UI Designer'
      },
      {
        'id': 3,
        'name': 'techpool',
        'job': 'Blogger'
      }
    ];
  }
}

Now the step 1 is completed!

Step 2 - Register service with injector

Where we register this service? Always remember to register it in the most super part of your applications. It depends on the application. Here, my super one is app.module.ts file. It bootstraps the AppComponent and the AppComponent bootstraps the other child components including user-list component. There are two steps..
1. Import the service to AppModule. 
2. Then include it in the providers meta data array.


app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { UserListComponent } from './user-list/user-list.component';

import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent,
    UserListComponent 
  ],
  imports: [
    BrowserModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now the step 2 is completed!

Step 3 - Declare as a dependency

Open the UserList component TS file. Now we have to import the service here also since we are going to display data in user-list.component.html file.
Then a local variable should be declared in the type of UserService, within the constructor of the UserService class. This variable contains an instance of UserService.

Next part is fetching the data using the defined method. For this we use ngOnInit lifecycle hook available in Angular. This hook gets called once a component has been initialized.

user-list/user-list.component.ts


import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
  public users: any[] ;
  constructor(private _userService: UserService) { }

  ngOnInit() {
    this.users = this._userService.getUsers();
  }
}

Now UserService has been provided to UserList component! We can display the data in user-list.component.html file that are fetched from getUsers method. This is the code for the template.

user-list/user-list.component.html


<div class="container">
    <div class="row">
      <div class="col-lg-3"></div>
      <div class="col-lg-6">
          <h3 class="text-center">List of Users</h3><br>
          <table class="table table-bordered">
            <thead>
              <th>ID</th>
              <th>Name</th>
              <th>Job</th>
            </thead>
            <tbody>
              <tr *ngFor="let item of users">
                  <td>{{ item.id }}</td>
                  <td>{{ item.name }}</td>
                  <td>{{ item.job }}</td>
              </tr>
            </tbody>
          </table>
      </div>
      <div class="col-lg-3"></div>
    </div>
    <br>
  </div>

Now the step 3 is completed!

As the final part, we need to load the UserList Component through the AppComponent, in order to be displayed in the browser. We use the selector of the UserList component for this task. So, open app.component.html file and place this code.

app.component.html


<div style="text-align:center; margin-top: 30px;">
  <app-user-list></app-user-list>
</div>


Now navigate into the project from your cmd and type  ng serve -o  to open the project in web browser. It should be like this..
We have come to end of this article. We created a service and fetched the defined data in an array. The main use of these services is sharing data with components. All the methods are defined within the service class. Here we fetched data from an array as an example. But when it comes to the real use, we have to fetch data from a database or a file. So my next article will fetch data from a JSON file. We can use Angular services to manage data with a Web API written in PHP also..That is the advanced use..

Hope you got the knowledge to use services in Angular.. Wait more on services from TechPool..

Good Bye!





1 Comments

  1. Very useful article! To support Angular Web Development I would also like to share that 968,139 live websites are using Angular JS. Constantly, Top Angular Web Development Company are growing rapidly with the increasing demands of Angular Web development.

    ReplyDelete