How to call a function in one page to another in ionic 2

Lets say i have in function getUserDetails() in my login.ts and i want to call this function again in my register.ts so that i could i avoid code repeatation. Can anyone suggest me a solution. An example will be much appreciated…

Inject the same provider into both pages.

Could you explain…and can you show an example

Read the Angular docs on dependency injection.

You should put your shared function in a provider.

Hi,

Maybe watch this video from Josh Morony
To youtube

A provider provide a sort of ‘global’ function. If in you provider named User.ts you have a function called getNames(), and this function return a string like return "I'm a string";.

So in you pageName.ts import this provider and call this.user.getNames(), or console.log(this.user.getNames()); to see the result of the getNames() function from the provider. So you can import this provider in your pages and call this function anytime you want. Really basic explanation.

This is the gist and will hopefully give you more information to find your answer.

You’ll need to learn how Providers work. This may seem hard at first , but give an hour and it will make complete sense. Providers are basically data I/O routines or things that don’t require a UI.

Generate your Provider: ionic g provider user-gateway

Then … this sounds redundant BUT! with Ionic everything is redundant and it sounds redundant :slight_smile: You will need to IMPORT your provider into the app.module AND declare it as a provider in the providers array of the @NgModule decorator. If that sounds confusing … I can post an example.
AND you have to do this again in the Page in order for the page to use the Provider. IMPORT into the Page’s .ts … but instead of declaring it in .module you INJECT it onto the constructor method.

import {UserGatewayProvider } from '../../providers/user-gateway/user-gateway';

constructor(public navCtrl: NavController, public navParams: NavParams, public myGateKeeper: UserGatewayProvider) { .... }
type or paste code here


now my  object  myGateKeeper  has the SAME methods as my service ;)

can we do same without using a providers

Yes we can use providers.