What Is Angular 2 Service? (Steps For Create and Use of Angular 2 Services)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

What is Angular 2 Service?

[Steps For Create and Use of Angular


2 Services]
What is an Angular 2 Service?
Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it
result as a service for across your application.

What are the features of Angular 2 Service?


The Angular 2 is using services concept and it provide the multiple features to us that are,
1. Services are singleton objects.
2. Services are capable of returning the data in the form promises or observables.
3. Service class is decorated with Injectable decorator.
4. The Injectable decorator is required only if our service class is making use of some Angular
injectable like Http, Response and HttpModule service within it.

What are the differences between Observables & Promises?


1. Promise:- Promises are only called once and It can return only a single value at a time and the
Promises are not cancellable.
2. Observables:- Observables handle multiple values over time and it can return multiple values
and the Observables are cancellable.
3. The Observables are more advanced than Promises.

Steps for creating an Angular 2 Service:-


There are four steps as,
1. Import the injectable member i.e.
import {Injectable} from '@angular/core';
2. Import the HttpModule, Http and Response members’ i.e.
import { HttpModule, Http, Response } from '@angular/http';
3. Add the @Injectable Decorator i.e. @Injectable()
4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }
}

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-


There are four steps to calling a service in component as,
1. Create or Import the Service to the component class.
2. Add it as a component provider.
3. Include it through Dependency Injection.
4. Use the Service function in the component.
In the below Example,
I hope this will help you to understand and create the basic of Angular 2 service. I am creating a
user service and this user service returns the list of users.

After creating user service, I will use the user service “getUsers()” method in the user
component’s ngOnInit() method to load the returns user collections on user screen.

I am also using the REST API Url (https://api.github.com/users/hadley/orgs) and this RESTful API
will returns the users.

app.module.ts :-

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


import { RouterModule, Routes } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './components/app/app.component';
import { UserComponent } from './components/user/user.component';
import { HeaderComponent } from './components/shared/header/header.component';
import { MenuComponent } from './components/menu/menu.component';
import { LoginComponent } from './components/login/login.component';
import { RegistrationComponent } from './components/registration/registration.component';

@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
UserComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS
BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
RouterModule.forRoot([ //RouterModule.forRoot method in the module imports to
configure the router.
{ path: '', redirectTo: 'user', pathMatch: 'full' },
{ path: 'user/:id', component: UserComponent }, //HERE ID IS A ROUTE
PARAMETER.
{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '**', redirectTo: 'user' }
]),
FormsModule,
ReactiveFormsModule
]
})
export class AppModule {
}

user.component.ts and user.service.ts :-

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


import { CommonModule } from '@angular/common';
import { HttpModule, Http, Response } from '@angular/http';

//BEGIN-REGION - USERSERVICE
@Injectable()
export class UserService {
constructor(private _http: Http) { }

getUsers(apiUrl) {
return this._http.get(apiUrl).map((data: Response) => data.json());
}
}
//END BEGIN - USERSERVICE

//BEGIN-REGION - USERCOMPONENT
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService]
})

export class UserComponent {


//USERS DECLARATIONS.
users = [];

//FETCHING JSON DATA FROM REST APIS


userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR


constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.


ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data => this.users =
data);
}
}
//END BEGIN – USERCOMPONENT

user.component.html :-

<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h2>Angular 2 - User Services</h2>
</div>
<hr />
<div class="ibox-content">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>Description </th>
<th>URls </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users; let i = index">
<td>{{user.id}}</td>
<td>{{user.login}}</td>
<td>{{user.description}}</td>
<td><a href="{{user.public_members_url}}"> {{user.public_memb
ers_url}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>

Result :-
Features Of Angular 2 Services [Observables vs. Promises]
What are the features of Angular 2 Service?
The Angular 2 is using services concept and it provide the multiple features to us that are,
1. Services are singleton objects.
2. Services are capable of returning the data in the form promises or observables.
3. Service class is decorated with Injectable decorator.
4. The Injectable decorator is required only if our service class is making use of some Angular
injectable like Http, Response and HttpModule service within it.

What are the differences between Observables & Promises?


1. Promise:- Promises are only called once and It can return only a single value at a time and the
Promises are not cancellable.
2. Observables:- Observables handle multiple values over time and it can return multiple values
and the Observables are cancellable.
3. The Observables are more advanced than Promises.

What are the differences between Angular 2 Observables &


Promises?
What are the features of Angular 2 Service?
The Angular 2 is using services concept and it provide the multiple features to us that are,
1. Services are singleton objects.
2. Services are capable of returning the data in the form promises or observables.
3. Service class is decorated with Injectable decorator.
4. The Injectable decorator is required only if our service class is making use of some Angular
injectable like Http, Response and HttpModule service within it.

What are the differences between Observables & Promises?


1. Promise:- Promises are only called once and It can return only a single value at a time and the
Promises are not cancellable.
2. Observables:- Observables handle multiple values over time and it can return multiple values
and the Observables are cancellable.
3. The Observables are more advanced than Promises.
How To Create & Call Angular 2 Service s in Components?
What is an Angular 2 Service?
Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it
result as a service for across your application.

What are the features of Angular 2 Service?


The Angular 2 is using services concept and it provide the multiple features to us that are,
1. Services are singleton objects.
2. Services are capable of returning the data in the form promises or observables.
3. Service class is decorated with Injectable decorator.
4. The Injectable decorator is required only if our service class is making use of some Angular
injectable like Http, Response and HttpModule service within it.

Steps for creating an Angular 2 Service:-


There are four steps as,
1. Import the injectable member i.e.
import {Injectable} from '@angular/core';
2. Import the HttpModule, Http and Response members’ i.e.
import { HttpModule, Http, Response } from '@angular/http';
3. Add the @Injectable Decorator i.e. @Injectable()
4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }
}

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-


There are four steps to calling a service in component as,
1. Create or Import the Service to the component class.
2. Add it as a component provider.
3. Include it through Dependency Injection.
4. Use the Service function in the component.

Angular 2 http Service Requests with Example


Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it
result as a service for across your application.

The Angular 2 is using services concept and it provide the multiple features to us that are,
1. Services are singleton objects.
2. Services are capable of returning the data in the form promises or observables.
3. Service class is decorated with Injectable decorator.
4. The Injectable decorator is required only if our service class is making use of some Angular
injectable like Http, Response and HttpModule service within it.
Steps for creating an Angular 2 Service:-
There are four steps as,
1. Import the injectable member i.e.
import {Injectable} from '@angular/core';
2. Import the HttpModule, Http and Response members’ i.e.
import { HttpModule, Http, Response } from '@angular/http';
3. Add the @Injectable Decorator i.e. @Injectable()
4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }
}

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-


There are four steps to calling a service in component as,
1. Create or Import the Service to the component class.
2. Add it as a component provider.
3. Include it through Dependency Injection.
4. Use the Service function in the component.

You might also like