Google News
logo
Ionic - Interview Questions
What are the different ways to transfer data between Ionic Pages.
For every mobile app, it is very essentials to transfer its state between the components or pages. Ionic has few ways of doing it, which is listed below.
 
Using NavigationController : In Ionic 2 and 3 we can use the Navigation controller to pass data between the pages.
* Ex: If we have to travel between Page A to Page B, below code can be used to navigate and transfer the data.
* this.navCtrl.push(B, {name: ‘test’}) Where navCtrl is an object of NavigationController.
* To get the value of name on Page B below code is used.
* this.navParams.get(“name”) where navParams is an object of NavParams.

Using services : You can use a common service to transfer data between multiple pages.
Say you create a service named base and it has a variable name and email.
Page A can set the value of the variable by using this.base.email
Page B can access this variable by this.base.email whatever the value set by Page A can be used by Page B.

Complete code snippet :

1. Base service
@Injectable()
export class BaseProvider {
email:any;
}
2. Page A
import { BaseProvider } from "YOUR_PATH";
@IonicPage()
@Component({
  selector: 'page-A',
  templateUrl: 'a.html',
})
export class a {
    constructor(private base: BaseProvider){
        this.base.email = "test@test.com"
    }
}
3. Page B
import { BaseProvider } from "YOUR_PATH";
@IonicPage()
@Component({
  selector: 'page-A',
  templateUrl: 'a.html',
})
export class a {
    constructor(private base: BaseProvider){
        console.log(this.base.email)  //whatever set on page A can be accessed here
    }
}
Advertisement