Friday, 15 September 2017

Services - Angular2

An Angular 2 service is simply a javascript function, along with its associated properties and methods, that can be included (via dependency injection) into Angular 2 components. They allow you to develop code for specific tasks that can be used in those components.

Instead of copying and pasting the same code over and over, you'll create a single reusable data service and inject it into the components that need it. Using a separate service keeps components lean and focused on supporting the view, and makes it easy to unit-test components with a mock service.

In this tutorials, I am going to create services for adding and getting citylist.

1- Use the Project that you have created before for Inheritance - Angular 2.
2- Add a new folder named "Service" in src/app directory.
3- Change the directory and Create Service from terminal.
       cd src\app\Service  <Enter>
       ng g s City <Enter>

See the below image:

the above command will create a city.service.ts file and a spec file. ignore the spec file for now.

4- Add the function for adding and getting city list in service. Look the below code.

city.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class CityService {

cityList: string[] = [];
constructor() { }

AddCity(city: string) {
this.cityList.push(city);
}

GetCities(): string[] {
return this.cityList;
}
}

5- Now, Your Service is ready to use. Create a Component to use Service functions. in the app directory create a folder "ServiceComponent" and change the directory in terminal.

                          cd..<Enter>
                          cd src\app\ServiceComponent <Enter>
                          ng g c City -is --flat --spec false <Enter>

 The above command will create a CityComponent.

Importing the Service to your Components
You can either import your service directly within the components, or you can import them to the app.module.ts file, which will give all of your components access to that service. We'll show you both ways.

Import the Service to your Component

Choose a component file (CityComponent) and at the top, you must include the service member
(line 2 below):

import { Component, OnInit } from '@angular/core';
import {CityService} from '../Service/city.service'

Add it as a Provider

Now you must add it to the providers array in the Component decorator metadata (line 5 below):

@Component({
selector: 'app-city',
templateUrl: './city.component.html',
styles: [],
providers:[CityService]
})

Include it through depedency injection

In the constructor arguments of the component class, we include it through dependency injection:

constructor(private cityService: CityService) {
}

Using the Service

Now we can access the service's methods and properties by referencing the private cityService.
For example:

ngOnInit() {
this.cityList = this.cityService.GetCities();
}

AddCity() {
this.cityService.AddCity(this.city);
}

Here's the full code of the component above.

City.Component.ts
import { Component, OnInit } from '@angular/core';
import { CityService } from '../Service/city.service';

@Component({
selector: 'app-city',
templateUrl: './city.component.html',
styles: [],
providers:[CityService]
})
export class CityComponent implements OnInit {
city: string;
cityList: string[];
constructor(private cityService: CityService) {
}

ngOnInit() {
this.cityList = this.cityService.GetCities();
}
AddCity() {
this.cityService.AddCity(this.city);
}
}

City.Component.html
<h3>City Component</h3>
<input type="text" [(ngModel)]="city" /><button type="button" (click)="AddCity()">Add</button>

<h4>City List</h4>
<ul>
<li *ngFor="let item of cityList">{{item}}</li>
</ul>

One more change you need to do is, you have to import FormModule in your appModule.ts file.

import{FormsModule} from '@angular/forms';

Set the FormsModule in @NGModule Decorator.

imports: [
BrowserModule, FormsModule
],

Now your Service and Component is ready to use.

Including the Service in app.module.ts

The only step that differs when including a service in the app.module.ts from including it in a specific component is that you're declaring the service in the providers property of the app.module.ts @NgModule metadata, as opposed to the @Component's meta data:

In app.module.ts:
import{FormsModule} from '@angular/forms';
import { CityComponent } from './ServiceComponent/city.component';
import { CityService } from './Service/city.service';

@NgModule({
declarations: [
AppComponent,
CityComponent
],
imports: [
FormsModule
],
providers: [CityService],
bootstrap: [CityComponent]
})
export class AppModule { }

Now all Components within our application will have access to CityService. We no longer need to include CityService in a providers array within the component's metadata.  We do still need to import the CityService at the top of the components that we wish to use.

Bootstrap the component and run your application. Seet the output.




0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)