ionic2 Using Services Share information between different pages


Example

One of the easiest examples of using shared services is when we want to store some data from a given page of our application, and then get that data again but from another page.

One option could be to send that data as a parameter (for instance, if one page calls the other one) but if we want to use that data from a completely different part of the application, that seems to be not the best way to do it. That's when shared services comes to play.

In this example, we're going to use a simple service called MyService which only has two simple methods: saveMessage() to store a string and getMessage() to get it again. This code is part of this working plunker where you can see it in action.

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

@Injectable()
export class MyService { 
  
  private message: string;
  
  constructor(){ }
  
  public saveMessage(theMessage: string): void {
    this.message = theMessage;
  }
  
  public getMessage(): string {
    return this.message;
  }
}

Then, when we want to store a new message, we can just use the saveMessage(theMessageWeWantToSave); method from the MyService instance (called just service).

import { Component } from "@angular/core";
import { MyService } from 'service.ts';

@Component({
  templateUrl:"page1.html"
})
export class Page1 {
  
  message: string;
  
  // ... 
   
  public saveSecretMessage(): void {
    this.service.saveMessage(this.message);
  }      
}

In the same way, when we want to get that data we can use the getMessage() method from the service instance like this:

import { Component } from "@angular/core";
import { MyService } from 'service.ts';

@Component({
  templateUrl:"page2.html"
})
export class Page2 {
  
  enteredMessage: string;
  
  constructor(private service: MyService) {
    this.enteredMessage = this.service.getMessage();
  }
    
  // ...
}

Please remember to check the Remarks section to see where should the reference for the MyService service be included and why.