Friday, 15 September 2017

Services - Angular

An Angular service is simply a javascript function, along with its associated properties and methods, that can be included (via dependency injection) into Angular 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.

To register a service with the root injector we use providers property of @ngModule decorator and to register a service with the injector at a component levet use providers property of @Component decorator.

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


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives