Home >>Angular 6 Tutorial >Angular 6 Services

Angular 6 Services

Angular 6 Services

We may face situations where some code is needed to be used everywhere on the page. It can be for the connection of data that must be shared across components, etc. Services help us do that. Through services we are able to connect methods and properties across the whole project through certain components.

We need to allow use of command line to create a function. The same order is –


C:\projectA6\Angular6App>ng g service myservice
CREATE src/app/myservice.service.spec.ts (392 bytes)
CREATE src/app/myservice.service.ts (138 bytes)

The files generated at the bottom are next-myservice.service.specs.ts and myservice.service.ts.

myservice.service.ts


import { Injectable } from '@angular/core';
@Injectable()
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 must 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 { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      RouterModule.forRoot([
         {
            path: 'new-cmp',
            component: NewCmpComponent
         }
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})
export class AppModule { }

The Service has been introduced with the class name and the same term is included in the providers. Switch to the service class now and build a service role.

We will create a function in the service class which displays the date of today. Throughout the main parent component app.component.ts, and even in the new component new-cmp.component.ts we generated in the previous chapter, we may use the same feature.

Let's see now how the feature looks and how to use it in components in the operation.


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

We also built a feature showTodayDate in the service file above. Now we are going to return the created new 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 6 Project!';
   todaydate;
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
   }
}

In any part created the function ngOnInit is named by default. The date as seen above is fetched from the service. We need to include the service in the feature ts file first to get further information of the process.

In the.html file we must view the date as seen below −

{{todaydate}}
<app-new-cmp></app-new-cmp> 
// data to be displayed to user from the new component class.

Let us now see how to use the service in the new component created.


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;
   newcomponent = "Entered in new component created";
   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 developed, and access the methods and properties of the same. Please see underlined code. The html component shows today's date as follows –


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

When you adjust the utility property of some feature, the same goes for those components as well. Let's see what this looks like now.

In the provider, we must identify 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.

We have created a property in myservice.service.ts and used the same in other parent and new component.


import { Injectable } from '@angular/core';
@Injectable()
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 control 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 4 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 function on console.log. We will convert the value of the variable into "component created" in the next paragraph. 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 section above, we do not change anything but directly assign the property to the property of the component.

So as you run it in the browser, the utility property will be modified because the meaning of it will be updated in app.component.ts and the same will be seen for new-cmp.component.ts.