Angular 4 Service Tutorial

During developing Angular application we come across a situation where we need to write some lines of code everywhere inside our application. One simple way is to write code everywhere that is needed, but that is not good practice specially when we are using frameworks because frameworks are basically build for making our coding effort less and arrange file and folders in a better way.

With help of Services we can be able to access methods and properties across other components inside entire Application.

To create a Service we have to need to write simple command


ng g service service_name

Inside this case I have created two component i.e home and servicecheck and a service servicetest as shown inside image. Look at image carefully and we will find that after executing angular-cli command for creating services two files are automatically generated as in this case servicetest is name of service and two new files servicetest.service.spec.ts and servicetest.service.ts are generated as shown below inside application folder structure.

If we are beginner then in this phase we should not think more about servicetest.service.spec.ts  file because this is used during testing of application in this case we have to consider only about servicetest.service.ts which looks like


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

@Injectable({
  providedIn: 'root'
})
export class ServicetestService {

  constructor() { }
}

In this case Injectable module is imported from @angular/core. It contains @Injectable method and ServicetestService class. Now you can create properties or method that you want to access inside entire application.

Suppose we want to print date on my homepage then for this purpose we have to add

Before injecting service inside our application we have to need to include service inside app.moule.ts file and way to include service inside app.module.ts file is add inside provider array like.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
//import components 
import { HomeComponent } from './home/home.component';
import { ServicechekComponent } from './servicechek/servicechek.component';
//import service test
import { ServicetestService } from './servicetest.service';
//import Router Link
import {RouterModule,Router} from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ServicechekComponent
  ],
  imports: [
    BrowserModule,
//RouterModule
    RouterModule.forRoot([
      {path:'home',component:HomeComponent},
      {path:'servicechek',component:ServicechekComponent}
    ])
    
  ],
  providers: [HomeComponent,ServicechekComponent],
  bootstrap: [AppComponent]
})
export class AppModule {

 }

In above code I think if you are absolutely new in Angular 4 then little bit confused in RouterModule code


RouterModule.forRoot([
      {path:'home',component:HomeComponent},
      {path:'servicechek',component:ServicechekComponent}
    ])

Router is basically used for navigation between pages in Angular if we talk in terms of background then it is navigation between one component to other component. We talk in details about Router in upcoming post. Don’t panic for that.

Now come to app.component.html file I have not removed previous content which is generate by Default.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ ul >

Now we make some changes for navigating from one page to another page and for that we will make some changes inside our app.component.html file.


<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2>
      <a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a>
    </h2>
  </li>
  <li>
    <h2>
      <a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a>
    </h2>
  </li>
  <li>
    <h2>
      <a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular Blog</a>
    </h2>
  </li>
  <li>
    <a [routerLink]="['/home']">Home</a>
  </li>
  <li>
    <a [routerLink]="['/servicechek']">Service Check</a>
  </li>
  <li>
    <a [routerLink]="['/']">Back</a>
  </li>
</ul>
<router-outlet></router-outlet>
<!-- Routed components go here -->

It’s time to make changes inside service class for final out


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

@Injectable({
  providedIn: 'root'
})
export class ServicetestService {
  constructor() { }
//create a method for finding date
  public getDate() {
    let date = new Date();
    console.log(date);
    return date;
  }
}

How to include Service inside Component?

For including service inside Component we have to make such changes inside component, we have to make changes inside component.html and component.ts file.As we have already generated two components first one is home component and second one is servicecheck component.

Home Component

  • home.component.html
  • home.component.ts

home.component.ts


import { Component, OnInit } from '@angular/core';
import { ServicetestService } from '../servicetest.service';
// import {ServicetestService} from ''

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
 public todate;
  constructor(public servicech:ServicetestService) { 
    console.log("constructor is called ...");

  }
  //ngOnInit method calls at first 
  ngOnInit() {  
    console.log("Ng OnInit method is called .....");
    this.todate=this.servicech.getDate();
  }

}

home.component.html


<p>
 Today is : {{todate |date}}
</p>

It is our root page

root-page

Now click on home tab as highlighted inside image and we will find our desired output as shown below.

home-service-page


Leave a Reply

Your email address will not be published. Required fields are marked *