Services in Angular
Services: With services you can access methods, properties across other components
in entire project. To create a new service you just write command ng g service servicename
Following are the
files created at the bottom - employee-svc.service.specs.ts and employee-svc.service.ts.
employee-svc.service.ts
Here, the Injectable
module is imported from the @angular/core. It contains the @Injectable method
and a class called MyserviceService. We will create our service function in
this class.
In the service class, you
will create a function which will display today’s date. We can use the same
function in the main parent component app.component.ts and also in the new
component sharjeels-work.component.ts that I created in the previous chapter.
Let us now see how the
function looks in the service and how to use it in components.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EmployeeSvcService {
constructor() { }
showTodayDate() {
let ndate = new Date();
return ndate;
}
}
In the above service
file, we have created a function showTodayDate. Now we will return the new Date
() created. Let us see how we can access this function in the component class.
sharjeels-work.component.ts
import { Component, OnInit } from '@angular/core';
import { EmployeeSvcService } from './../Services/employee-svc.service';
@Component({
selector: 'app-sharjeels-work',
templateUrl: './sharjeels-work.component.html',
styleUrls: ['./sharjeels-work.component.css']
})
export class SharjeelsWorkComponent implements OnInit {
constructor(private empSvc: EmployeeSvcService) { }
todaydate;
ngOnInit() {
this.todaydate = this.empSvc.showTodayDate();
}
title = 'Data Binding In Angular 6';
employeeName = "Affan Baba";
The ngOnInit function
gets called by default in any component created. The date is fetched from the
service as shown above. To fetch more details of the service, we need to first
include the service in the component ts file.
We will display the
date in the .html file as shown below
sharjeels-work.component.html
<p>
{{title}}
</p>
<p>Today's date is
{{todaydate}}</p>
<p>{{employeeName}}</p>
Now build the app and
serve then you will get the output as current date display on your component. This
value actually coming from service which you added in your application.
Happy Learning!!!
Comments
Post a Comment