Angular.js

Angular 4: Service example

Welcome to Angular 4 services

Angular services are for building out code that can be shared across multiple components. And these are singletons. services restrict the instantiation of a class to one object. It means the methods and properties can be shared throughout your application from a single shared instance.

These services are best way to store the session data and perfect place to call the web services. And the data is shared to the components with the injecting service. Without hitting the web services we can use the session data in the application. But If you refresh the browser the session service data will be empty. So remember that condition.

In this tutorial, we provide a basic angular 2 service example using the Angular CLI.

We’ll be using the Angular CLI to create our app. Create a new Angular project by running:

ng new AngularServiceEx

This will create the new project named as AngularServiceEx project.

And navigate to root application by cd  AngularServiceEx. And run the below command

Npm install

This command will download all your dependencies from your package.json file.

And run the below command to create the service in the project.

ng g service reference

It will create the reference.service in the ’app’ folder automatically. We don’t need to do anything.  It will create the two files in our Angular app

  • a reference.service.tsfile under the src/app directory
  • a reference.service.spec.tsfile under the src/app directory

We will write the service code in the service.ts file.  And service.spec.ts file will used for unit testing.

The ng g service command won’t automatically configure your root module app.module.ts to provide the service.

Services must import the Injectable from the angular/core package, like below. see the angular. io website for more info on services.

import { Injectable } from ‘@angular/core’;

And services uses the  injectable decorator. @Injectable() . The @Injectable decorator simply provides dependency injection for the service.

Don’t forget to add the decorator in the service.ts file. If we don’t add it will not work.

Service must have the export keyword.  Everything like class or component should use ‘export’  keyword. Then only it is possible to use the class or component or anything in the project. And service name should end with .service.  For ex:  reference.service.ts file. If we have lengthy name we need add the ‘–‘ in the service name. That is for code readability.

Example: save-user-info.service.ts

Service structure:

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

@Injectable()

export class ReferenceService {

constructor() {  console.log(“welcome! Reference Service”);  }

}}

To include the service in your app, you must import it and include it as a provider in app.module.ts or we can add the service in providers of component meta data also. But it will be available in the particular component only. But it’s better to use the service in the providers of app.module.ts. Service will create the instance every time, whenever you come to the component.  By registering the service as a provider, you make it available everywhere in the application.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReferenceService } from './reference.service'

@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule ],
providers: [ReferenceService],
bootstrap: [AppComponent]
})

export class AppModule { }

Accessing the Service from a component:

app.component.ts

Services must be imported by the component. We will import our reference service in open the auto-generated app.component.ts and replace it with the following:

import { Component } from '@angular/core';
import { ReferenceService } from './reference.service'

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
constructor(public reference: ReferenceService){

}
}

Service with HTTP methods :

We will have to interact with Database to get the data and post the data. For that we will write the web service api in the Angular services. We will have to call the HTTP POST or HTTP GET methods with REST API in the service to store that data in the DATABASE or retrieve the data from the DATABASE.

Let’s see the Example with real Json file:

We will use the Reference Service. And we will write the http method in the reference service. That http method should be called in the component methods to get the data or post the data to the REST side. For now will go through with angular services with Json file.Will add one json file in the project. In the angular every request and response will be in the Json  only. You need to add the json file in the assets folder under src folder of your project. You may get 404 json file not found, if you add the json file somewhere other than assets location folder.

Json file:

Created the json folder in the assets folder in ‘src/assets’. See example json data.

[

{ “id”: 10, "firstName":<em>"Sathish"</em>, "lastName":<em>"Kotha"</em> },

{ “id”: 11, "firstName":<em>"Ramesh"</em>, "lastName":<em>"Kotha"</em> },

{ “id”: 12, "firstName":<em>"Ragav"</em>, "lastName":<em>"Raju"</em> }

]

Employee class:

We need to create the Employee model class. It’s a type of json data, remember every where we need export the class. This model class is a typescript format. Type the below command.

ng g class Employee

This will create the Employee model class in the app folder.

typically you declare types in a model which can then be reused throughout the rest of the application. With TypeScript, frontend applications can now benefit from strongly typed models!

This is pretty straightforward for declaring individual variables,

A simple example of this is a Employee class that defines a firstName and lastName variables that’s are string and an id variable that must be a number:

export class Employee  {

id: number;

firstName: string;

lastName: string;

}

Service:

In the service, we will  import the Http from “@angular/http”; with http we will use the http get the post and request methods. To get the all the methods we need to include the http in the constructor. for more info on http please refer https://angular.io/tutorial/toh-pt6

And import some rxjs. These are reactive extension java script. Rxjs is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js. We will use some methods from the Rxjs in angular services like map and observable and catch. We will use these in the services.

Don’t instantiated the service with new keyword, it will create error prone and memory leak.

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

import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';

import { Employee } from './employee';

@Injectable()

export class ReferenceService {

constructor(private http: Http) { }

getAllEmployees(): Observable< Employee > {

try {

return this.http.get(‘assets/service.json') .map(this.extractdata).catch(this.handleerror) ;

// Api Full path like, http://localhost:4200/assets/service.json

}   catch (error) { console.log(error); }  }

extractData(res: Response) {

const body = res.json();

return body || {};   }

handleError(error: any) { return Observable.throw(error); }
}

In the above service  http reference is used to call the http methods. We created one method is get all employees, we are calling http.get method with json link. This get method will get the json data. Then it will come to  map method, it is used to extract the JSON content from the response coming as the observable type. if you got any error while calling the http method it will come to catch method,from there it will directly throw the error with observable throw method.

Component:

Import the reference service in the component as below and one more thing we need the ngOn Init life cycle method. Every component has to implement the ngOnInit method. And this method will call after the constructor. It’s used like a main method. When you come to component, ng On Init method will call, you can call any number of methods in the ngOnInit method.

import { Component, OnInit } from '@angular/core';

import { ReferenceService } from './reference.service';

import { Employee } from './employee';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']  })

export class AppComponent implements OnInit  {

title = 'Angular Service app';

employeesInfo: any;

constructor(public referService: ReferenceService) { }

getAllEmployeesInfo() {

this.referService.getAllEmployees() .subscribe((result: Employee[]) => {

console.log('the employess data:' + result);

this.employeesInfo = result;      },

(error: any) => {  console.log('error in employees method');      });   }

ngOnInit() {  this. getAllEmployeesInfo();  }

}

In above component, service method is called in component method getAllEmployeesInfo with reference service http method. And when we got the output it will come to subscribe result.  There we are assigning the result to our variables. If we get any error when calling the api it will come to error block. This error will return from catch of Observable  throw error.

App.component.html:

<h1 style="text-align: center">  Welcome to {{title}}! </h1>

<h3 style="text-align: center">ALL employeesInfo here</h3>
<div style="text-align: center;">

<b>Emp ID</b> {{emp.id}}

<b>  First Name is :</b> {{emp.firstName}}

<b>Last Name is :</b> {{emp.lastName}}

</div>

Above html we are using title in curly brackets. It’s a two way bindings. Whatever we add it automatically convert the value. And one more new word is “*ngFor” structural directives. This is used to iterate the json data in the html. We have the multiple employes the data in the “ employessInfo”  variable. So we need to include the ng for here to iterate the data in the html. We add the reference value in the ng for. With that will call the inside object data.

Service used in the Module:

import { BrowserModule } from '@angular/platform-browser';

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

import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { ReferenceService } from './services/reference.service';

@NgModule({

declarations: [ AppComponent ],

imports: [ BrowserModule, HttpModule ],

providers: [ReferenceService],

bootstrap: [AppComponent] })

export class AppModule { }

Above app.module we have imported reference service and app component , All components should be added in the declarations field. And service should go to provides. Httmodule is also imported to imports. And last app component will be added in the bootstrap , bootstrap will added to project from here

if you don’t add the service in the providers you will get following error. One more thing we need to add the http module in the app module imports. Don’t add the http in the imports. If you don’t include. You will get below error.

EXCEPTION: No provider for service!

Clone the repository and install all it’s dependencies:

# Clone repo

git clone https://github.com/Sathishchary/AngularServiceEx

# Enter into directory

cd AngularServiceEx

# Install dependencies

npm install

Published on Web Code Geeks with permission by Ramesh Kotha, partner at our WCG program. See the original article here: Angular 4: Service example

Opinions expressed by Web Code Geeks contributors are their own.

Ramesh Kotha

Ramesh is a certified Java professional working in financial domain, He is an application developer and has hands on practice with Java and related technologies. He is passionate about Spring and other open source technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
name name
name name
6 years ago

Hi,
You forgot to use *ngFor in App.component.html in your example.

Back to top button