Home >>Angular7 Tutorial >Angular7 Services

Angular7 Services

Angular7 Services

We can encounter a situation where some code is required to be used everywhere on the page. For example, it may be necessary to share between components for data connection. This is done through Services. With services we are able to access methods and properties across the entire project through many components.

We need to use the command line to create a service 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)

myservice.service.ts


import { Injectable } from '@angular/core';
@Injectable({
   providedIn: 'root' 
}) 
export class MyserviceService {
   constructor() { }
}

Here, it imports the injectable module from the @angular / core. It includes the method @Injectable, and a class called MyserviceService. Within this class we will build our service function.

We need to include the service created within the main parent app.module.ts before creating a new service.

	
		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 providers use the same class. Now let's switch back to service class and create a function for service.

We will build a function in the service class which displays the date of today. In the main parent component app.component.ts, and also in the new component new-cmp.component.ts we created in the previous chapter, we can use the same function.

Now let's see how the function looks in the service and how components are used.


import { Injectable } from '@angular/core';
@Injectable({ 
   providedIn: 'root' 
}) 
export class MyserviceService { 
   constructor() { } 
   showTodayDate() { 
      let ndate = new Date(); 
      return ndate; 
   }  
}

We have created a function showTodayDate in the service file above. Now we are going to return the new created Date). Let's see how that function can be accessed 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(); 
   } 
}

In any component generated the function ngOnInit is named by default. The date as shown above is fetched from the service. We need to include the service in the component ts file first to get more details of the service.

In the.html file we will display the date as shown below –

app.component.html

{{todaydate}} 
<app-new-cmp></app-new-cmp>

Let us now see how the service can be used in the new component that was 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(); 
   } 
}

We need to first import the service we want in the new component we have created, and access the methods and properties of the same. Check out the highlighted code. The html component shows today's date as follows –

new-cmp.component.html


<p> 
   {{newcomponent}} 
</p> 
<p> 
   Today's Date : {{todaydate}} 
</p>

App.component.html file uses the selector for the new component. The contents of the above html file display in the browser as shown below –

If you change the service property in any component, the same goes for other components as well. Let's see what this works like now.

In the module, we can define one element, and use it in the parent and the new part. We will change the property in the parent component again, and see if the new component changes the same thing or not.


import { Injectable } from '@angular/core';
@Injectable({ 
   providedIn: 'root' 
}) 
export class MyserviceService { 
   serviceproperty = "Service Created"; 
   constructor() { } 
   showTodayDate() { 
      let ndate = new Date(); 
      return ndate; 
   } 
}

In other components let's use the service property variable now. The variable we access in app.component.ts is 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; 
   } 
}

Now we're going to fetch the variable and work on console.log. We will change the value of the variable into "component created" in the next line. We 're going to do the same at 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 component above, we do not alter anything but directly assign the property to the property of the component.

Now when you execute it in the browser, the service property will be changed as the value of it will be changed in app.component.ts and the same will be shown for new-cmp.component.ts.

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 Sidebar ads