Angular Service
Angular service is used to define methods and properties and it can be used anywhere and everywhere inside a project. For eg, Api URL properties , DB connection, fetching data from API. in short a piece of code which needs to be used at many places inside a project. Such scenarios we can use service. A common place where we place the code and can be called from anywhere inside a project.
We can use below command to create a service.
ng g service common
Below screenshot show the output of the command.
We can see field common.service.ts and common.service.spec.ts is created
Common.service.ts created with below code.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CommonService { constructor() { } }
Now we need to add this service in app.module.ts so that it can be accessed across the project. Import the service and declare the same in providers
App.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MyfirstcomponentComponent } from './myfirstcomponent/myfirstcomponent.component'; import { CustomDirective } from './custom.directive'; import { SquarePipe } from './square.pipe'; import { HomeComponent } from './home/home.component'; import { ContactComponent } from './contact/contact.component'; import {CommonService } from './common.service'; @NgModule({ declarations: [ AppComponent, MyfirstcomponentComponent, CustomDirective, SquarePipe, HomeComponent, ContactComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [CommonService], bootstrap: [AppComponent] }) export class AppModule { }
Now lets create a common function to show current date in common.service.ts as below
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CommonService { constructor() { } showDate(){ let dt = new Date; return dt; } }
Lets see this function declared inside the service used with the home component. As usual we need to import the service in the home component, then initiate it with the constructor. ngOnInit method is available by default when we create a component.
import { Component, OnInit } from '@angular/core'; import {CommonService} from '../common.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private cs : CommonService) { } showdate: any; ngOnInit(): void { this.showdate = this.cs.showDate() } }
Home.component.html
<p>home works!</p> <h1> <p> Todays date : {{showdate}}</p> </h1>