We might come across a situation where we need some code to be used everywhere on the page. For example, it can be for data connection that needs to be shared across components. This is achieved with the help of Services. With services, we can access methods and properties across other components in the entire project.
To create a service, we need to make use of the command line as given below −
ng g service myservice
C:\projectA7\angular7-app>ng g service myservice CREATE src/app/myservice.service.spec.ts (348 bytes) CREATE src/app/myservice.service.ts (138 bytes)
The files created in app folder are as follows −
Following are the files created which are shown at the bottom ― myservice.service.specs.ts and myservice.service.ts.
myservice.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { constructor() { } }
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.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule , RoutingComponent} from './app-routing.module'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; import { MyserviceService } from './myservice.service'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { }
We have imported the Service with the class name, and the same class is used in the providers. Let us now switch back to the service class and create a service function.
In the service class, we 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 new-cmp.component.ts that we 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 MyserviceService { 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.
app.component.ts
import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; todaydate; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } }
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 −
app.component.html
{{todaydate}} <app-new-cmp></app-new-cmp>
Let us now see how to use the service in the new component created.
new-cmp.component.ts
import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; todaydate; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } }
In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Check the code highlighted. todaydate is displayed in the component html as follows −
new-cmp.component.html
<p> {{newcomponent}} </p> <p> Today's Date : {{todaydate}} </p>
The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below −
If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works.
We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not.
In myservice.service.ts, we have created a property and used the same in other parent and new component.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { serviceproperty = "Service Created"; constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } }
Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows −
import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; todaydate; componentproperty; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); console.log(this.myservice.serviceproperty); this.myservice.serviceproperty = "component created"; // value is changed. this.componentproperty = this.myservice.serviceproperty; } }
We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new-cmp.component.ts.
import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { todaydate; newcomponentproperty; newcomponent = "Entered in newcomponent"; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.newcomponentproperty = this.myservice.serviceproperty; } }
In the above component, we are not changing anything but directly assigning the property to the component property.
Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts.
Also check the value in the console before it is changed.
Here is the app.component.html and new-cmp.component.html files −
app.component.html
<h3>{{todaydate}}>/h3> <h3> Service Property : {{componentproperty}} </h3> <app-new-cmp></app-new-cmp>
new-cmp.component.html
<h3>{{newcomponent}} </h3> <h3> Service Property : {{newcomponentproperty}} </h3> <h3> Today's Date : {{todaydate}} </h3>
No comments:
Post a Comment