This angular 8/9 example tutorial help to create an Injectable service using angular 8/9. You can also follow the same process to create a service for angular 2 and angular4 applications, Sometimes we need to share some methods across the components, that can be shared between angular components using the Injectable service.
Angular 2+ provides an option to create shared services for common methods and functionality. We can create common methods into a single service file and use them in different components.
Let’s start with a simple angular 5 service example using angular CLI, I assumed you have created the angular 5 application, if not please create using angular CLI.
Checkout Other Angular tutorials,
- Local Storage and Session Storage In Angular 9
- Getting started with angular 9
- How to Convert Bootstrap 4 theme into Angular 9 Layout
Step 1: We will create a service using angular CLI.Go to the angular project and run the below command.
ng g service helper
The above command will create two files named helper.service.ts
and helper.service.spec.ts
into src/app
folder.
Step 2: We will add the following code into helper.service.ts
file.
import { Injectable } from '@angular/core'; @Injectable() export class HelperService { constructor() { } testHelper(){ console.log('hello'); return 'Called, Hellper method.'; } }
Step 3: Now Update the app.module.ts
file for the helper service and added into the provider’s list.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HelperService } from './helper.service'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [HelperService], bootstrap: [AppComponent] }) export class AppModule { }
Step 4: We will update app.component.ts file and add a helper service file reference, add the service name into provides as well.
import { Component } from '@angular/core'; import { HelperService } from './helper.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers:[HelperService] }) export class AppComponent { title = 'app'; constructor(public helper: HelperService) { this.helper.testHelper(); } }
We have assigned helper service instances to public helper
variable, We have called testHelper()
method into constructor.
Step 5: Finally run the application using the following command.
ng serve
Now open the browser and go to the http://localhost:4200
, you can see hello message into the console.