Where should I write general JS with Ionic 2


#1

Hey guys,

Some JS methods are general to all my pages, AdMob methods for example. As I want to fraction as much as I can my code, I want to put the AdMob snippet (or any other common JS snippets) to a “centralized” file, exactly as I do with app.scss for general css.

I figured I could use app.component.ts but I’m ensure how to import it to pages like intro.ts, I tried to use import { MyApp } from ‘…/…/app/app’; but it doesnt seems to be working, it says the method doesnt exists.

Any advice, please?

Thanks


#2

Steps to solve this.

Create a service (change NameOfServiceHere to whatever you are calling this):

ionic g provider NameOfServiceHere

Place and structure the code that you want to use within this service - your service will be located at:

src/providers/NameOfServiceHere.ts

Then import the service into the components where you want that to be used like so:

import { NameOfYourServiceHere } from ‘…/…/providers/NameOfYourServiceHere’;

And also add to your src/app/app.module.ts file like so:

import { NgModule, ErrorHandler } from ‘@angular/core’;
import { IonicApp, IonicModule, IonicErrorHandler } from ‘ionic-angular’;
import { MyApp } from ‘./app.component’;
import { HomePage } from ‘…/pages/home/home’;
import { NameOfYourServiceHere } from ‘…/providers/NameOfYourServiceHere’;

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, NameOfYourServiceHere]
})
export class AppModule {}

When calling the method for your service in your homepage component, for example, it will be something like the following:

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { NameOfServiceHere } from ‘…/…/providers/NameOfServiceHere’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

constructor(public navCtrl 	: NavController,
	    **public nosh 	: NameOfServiceHere**) 
{


someMethod()
{
	**this.nosh.methodYouWantToAccess();**
}

}