googleads
How To Create Angular Service And Access It In Multiple Components
Angular Web Development

Create An Angular Service And Access It In Multiple Components

Maintaining functions in services have many benefits because it can be written in one place and can be accessed from many components. So we can avoid the code redundancy also on other hand, if any function requires change then we can able to modify and track all the changes in single place. Therefore, this blog is completely aimed to illustrate how functions and variables defined in Angular services can be used in multiple components, To demonstrate this, we will create a application which allows to create and view the name and contact number information.

Create a angular application using the command “ng new application-name”. I named the application as “services-app. This will create a new angular application folder. The angular version used here is 7.0.4.

ng new services-app

To simplify the things, i didn’t use any database. To define the model of data that is going to be stored we need to create a file named contact.model.ts,  This will tell the angular that what type of data is to be stored. Here we have two fields named  “name and contactNo” for storing and displaying the same.

Contact.model.ts

export class Contacts {
constructor(
public name: string,
public contactNo: number
) { }
}

Here the contacts class is our domain model.

Angular services are used to encapsulates(hide) the backend calls to the database, complex business logic and also contain variables and functions that can be shared by multiple components. Now let’s create a service file using the command “ng generate service service-name”. Since the service file is going to contain common variables and functions which can be accessed by multiple components therefore i named it as “common”.

ng generate service common

This command will a create file named common.service.ts under the src/app folder. Here i declared a variable named “contactSet” of type contact.model which we created before. And also we wrote two functions, one to add a new contact(“addContact”) and other to list the contacts(“getContactList”).  

common.service.ts

import { Injectable } from '@angular/core';
import {Contacts} from './contact';
@Injectable({
providedIn: 'root'
})
@Injectable()
export class CommonService {
// public contactSet: Contacts[];
public contactSet: Contacts[] = [ ];
constructor() { }
addContact(newContact){
console.log(newContact)
this.contactSet.push(newContact)
console.log(this.contactSet)
}
getContactList(){
console.log(this.contactSet)
return this.contactSet;
}
}

Next we are going to have two component, The First component named create-contact.component, which will hold a form to create a new contact. 

create-contact.component.html

<div >
<h2>Create Your Contact</h2>
<a [routerLink]="['/list']" >View Saved Contacts</a>
<form #contactForm="ngForm" (ngSubmit)="addContact(contactForm)" novalidate>
<div class="form-group">
<label>Name</label>
<input type="name" class="form-control" id="name" name="name" ngModel #email="ngModel" required>
</div>
<div class="form-group">
<label>Contact No</label>
<input type="contactNo" class="form-control" id="contactNo" name="contactNo" ngModel #password="ngModel" required>
</div>
<div class="form-group">
<button type="submit" [disabled]="!contactForm.valid">Submit</button>
</div>
</form>
</div>

To make this ngForm work, import FormsModule in app.module.ts file and also don’t forget to add the FormsModule to the imports metadata property array. The import statement as follows, 

Related: How To Build Dynamic Components In Angular 6

import { FormsModule } from ‘@angular/forms’

create-contact.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import {CommonService} from '../common.service'
import { Router } from '@angular/router';
@Component({
selector: 'app-create-contact',
templateUrl: './create-contact.component.html',
styleUrls: ['./create-contact.component.css']
})
export class CreateContactComponent implements OnInit {
constructor(public contactservice: CommonService,public router: Router) { }
ngOnInit() {
}
addContact(CreateContactForm: NgForm){
var newContact = {};
newContact = CreateContactForm.value;
this.contactservice.addContact(newContact);
this.router.navigate(['/list']);
}
}

The second component  is component view-contacts, which contain function to display the list of all saved contacts.

view-contacts.component.html

<div>
Your Contact List:
<ul>
<li *ngFor="let contact of contactList">
{{ contact.name }} {{contact.contactNo}}
</li>
</ul>
<a [routerLink]="['/create']" >Create Another Contact</a>
</div>

view-contacts.component.ts

import { Component, OnInit } from '@angular/core';
import {CommonService} from '../common.service'
import { Router } from '@angular/router';
@Component({
selector: 'app-view-contacts',
templateUrl: './view-contacts.component.html',
styleUrls: ['./view-contacts.component.css']
})
export class ViewContactsComponent implements OnInit {
public contactList;
constructor(public contactservice: CommonService,public router: Router) {
this.contactList = contactservice.getContactList();
}
ngOnInit() {
}
}

To start accessing the service function in components, Follow these few steps.

  • First, import the service file in our component.

 

  • Secondly, we have to register the service with the providers array in app.module.ts, which maintains the list of all dependencies and provide the instance of all the dependencies to the injector. 

 

  • Finally, we have to define it in component’s constructor. So when a Component is instantiated, it knows that it requires a particular Service just by looking at its constructor. It then looks for a match in the providers array which in turn to return the instance of service to the Component. 

 

app.module.ts

 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CreateContactComponent } from './create-contact/create-contact.component';
import { ViewContactsComponent } from './view-contacts/view-contacts.component';
import {CommonService} from './common.service'
@NgModule({
declarations: [
AppComponent,
CreateContactComponent,
ViewContactsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [CommonService],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

 

<div>
<router-outlet></router-outlet>
</div>

To enable routing between  components, we need to define the component with corresponding path in app-routing.module.ts which is created under src/app folder. 

app-routing.module.ts

 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateContactComponent } from './create-contact/create-contact.component';
import { ViewContactsComponent } from './view-contacts/view-contacts.component';
const routes: Routes = [
{ path: 'create', component: CreateContactComponent },
{ path: 'list', component: ViewContactsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
app.component.html
<div>
<router-outlet></router-outlet>
</div>

 

Related: How To Use Angular 2 Pipes & Reuse In Multiple Components

Run the application using “ng serve” command and hit localhost:4200/create in the browser and the following screen will pop up.


Fill the form with contact information and hit submit button,


On submit click, the addContact function of service function is trigged from create-contact component and the contact value will be pushed to the array variable declared in the service file of type contact.model.

In the view-contacts component, the getContactList() service function is trigged upon the component initialization and displayed all the contact values that were stored in that “contactSet” service variable.

By creating this Angular service now we can able to access it in Multiple Components and some of the notable things are that we can maintain the organized code. Alongside, Variables declared in services can be modified by different components which becomes a shared variable. Hope it helps you!

Building a high performance sites in angular requires standard approach and more intellectual inputs so make sure to reach out the great minds of Angular web development service to suggest you the right way of proceedings.

One thought on “Create An Angular Service And Access It In Multiple Components”

  1. An excellently written article, if only all blogger offered the same level of content as you, the internet would be a much better place. Please keep it up!. Great tips, I would like to join your blog anyway. Waiting for some more review. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *