Ionic Service to share data between page

In Ionic Angular application contains the concept of ionic service: a class containing methods and properties that can be reused by injecting them across application components, directive, and another service. Service is a class which acts as a central repository, as a central business unit we could say something where you can store, where you can centralize your code is based on your application.

How to create ionic service. ?

We can create an ionic service manually or by using ionic cli to generate new service as.

ionic generate service serviceName

Why use of ionic service. ?

Here we have listed some of most important reason why we need service in Ionic application.

  1. Sharing data: sharing data across components, especially among not related components (parent/child relationship among components.
  2. Managing data state: In a small and medium application, we can use service and rxjs library to manage the state of data across the application. In the large application, you might use ngrx for reactive state management of data in Angular.
  3. Retrieving and sending data to a remote server from/to our application.

Example on how to use service in ionic?

In Ionic Angular, the components can communicate with each other in many ways for parent/child related component we can use input and even binding for sharing data. With service, we can easily share data among related and nonrelated components. In this example, we are creating a service called userService and by using this service when we change the data on the home page and change data can be display on a different page called confirm page.

In this example, we will learn
1. Sharing data among components or pages.
2. Detecting changes using getters and setters inside the service provider.

Step 1: ionic start sharedService blank –type=angular
The home page we display user information from service and add new user information name and age field to the service user.service.ts. We have confirm button and clicking on confirm in the home page will route us to confirm page where we can data of home page from userService.

ionic service example

Step 2 Create confirm page and user service as
>> ionic generate page confirm
>> ionic generate service user
Edit user.service.ts file and add get/set method to do additional processing when other pages access or set the variables in this common class.

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class UserService {
  private _name: string;
  private _age: number;

  get name() {
    return this._name;
  }

  set name(name: string) {
    this._name = name;
  }

  get age() {
    return this._age;
  }

  set age(age: number) {
    this._age = age;
  }
}

Step 3: Edit in home.page.html template file to add | edit user information.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic 6 Service
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div class="ion-padding">
    <ion-card>
      <ion-card-header>
        <ion-card-title>What you are entering</ion-card-title>
      </ion-card-header>

      <ion-card-content>
        <ion-badge color="secondary">Name</ion-badge>{{ user.name }}<br /><br />
        <ion-badge color="tertiary">Age</ion-badge> {{ user.age }}
      </ion-card-content>
    </ion-card>

    <ion-list>
      <ion-item>
        <ion-label position="fixed">Name</ion-label>
        <ion-input type="text" [(ngModel)]="user.name"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="fixed">Age</ion-label>
        <ion-input type="number" [(ngModel)]="user.age"></ion-input>
      </ion-item>

      <ion-item class="ion-float-right" lines="none">
        <ion-button color="primary" [routerLink]="'/confirm'">Confirm</ion-button>
      </ion-item>
    </ion-list>
  </div>
</ion-content>

Step 4: Edit n home.page.ts file where we have to inject userService service on our page so that we can use it.

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  user: any;

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.user = this.userService;
  }
}

Step 5: Edit confirm.page.html template to display data from the home page.

<ion-header>
  <ion-toolbar>
    <ion-title>Confirm</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-card>
    <ion-card-header>
      <ion-card-title>Please confirm your profile</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      {{ user.name }} is {{ user.age }} years old
    </ion-card-content>
    <ion-item float-right>
      <ion-button color="primary" [routerLink]="'/home'">Ok</ion-button>
    </ion-item>
  </ion-card>
</ion-content>

Step 6: Edit confirm.page.ts file

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-confirm',
  templateUrl: './confirm.page.html',
  styleUrls: ['./confirm.page.scss'],
})
export class ConfirmPage implements OnInit {
  user: any;

  constructor(private  userService: UserService) { }

  ngOnInit() {
    this.user = this.userService;
  }
}

Conclusion
We have completed the ionic service, why we need it, and how we can use it to share data among different components. I hope you got some idea on Ionic service usage and how to implement it.

Leave a Comment

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

Scroll to Top