Sunday, October 7, 2018

Service example in Angular 6

Services in Angular are classes which perform a specific / unit of work. Services with a well-defined purpose and help in modularizing the application design.

Components deal with the UI of the application, hence they delegate data specific operations like fetching data from server, validating data etc to Services. Since services are outside the component, they can be re-used by injecting into the required components, thereby enabling re-usability of shared service code.

To create a new service we need to use the ng generate cli command

ng generate service

In the following example we shall create a very simple service hello.service, which has a function getMessage(), the function just returns a string message. We shall use this service in a component and display the message returned by the service in the component UI.

First let us create the service by running the cli command.

ng generate service hello

This will create 2 files.
hello.service.ts
hello.service.spec.ts


Here the .spec.ts file is for test cases, we will not get into this for now. Let us open the hello.service.ts file and add the following code.

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

@Injectable({
  providedIn: 'root'
})
export class HelloService {
  constructor() { }
  getMessage() {
       return "Hello from Service";
  }
}

Once we have the service ready, let us inject this service into a component, use the service method getMessage(), get the message and display it in the component. Let us add the following code to the component to use the service.

import { Component } from '@angular/core';
import { HelloService } from './hello.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private svcHello: HelloService) { }
  title = 'Angular 6';
  message = this.svcHello.getMessage();
}

Notice that we are injecting the service in the constructor of the component, this way we can use the properties and methods of the service in the component.

Finally we will use this property message in the view template and display the message in the UI.

<div style="text-align:center">
  <p class="title">Welcome to {{ title }}!</p><br>
  <p class="msg">Message from Service:  {{ message }}!</p>
</div>

The output is as follows.






Search Flipkart Products:
Flipkart.com

No comments: