Injecting service into tabs ionic 2


#1

I’m following this tutorial advanced google maps component in ionic 2.
I made it step by step and works perfectly but in single pages only. On my project I’m planning to use tabs or sidemenu design.
I’ve already asked on the blog of this tutorial but still no responses.
Thanks in advance any help or advice will be apreciated.
map.js:

import {Page, NavController} from 'ionic-angular';
import {ConnectivityService} from '../../providers/connectivity-service/connectivity-service';

@Page({
  templateUrl: 'build/pages/map/map.html',
})
export class MapPage {
  static get parameters() {
    return [[NavController], [ConnectivityService]];
  }
  constructor(nav,connectivityService) {
    this.nav = nav;
    this.connectivity = connectivityService;
 
    this.map = null;
    this.mapInitialised = false;
    this.apiKey = null;
 
    this.loadGoogleMaps();
  }

    loadGoogleMaps(){
    var me = this;
    this.addConnectivityListeners();
    if(typeof google == "undefined" || typeof google.maps == "undefined"){
        console.log("Google maps JavaScript needs to be loaded.");
        this.disableMap();
        if(this.connectivity.isOnline()){
            console.log("online, loading map");
            //Load the SDK
            window.mapInit = function(){
                me.initMap();
                me.enableMap();
            }
            let script = document.createElement("script");
            script.id = "googleMaps";
            if(this.apiKey){
                script.src = 'http://maps.google.com/maps/api/js?key=' + apiKey + '&callback=mapInit';
            } else {
                script.src = 'http://maps.google.com/maps/api/js?callback=mapInit';               
            }
            document.body.appendChild(script);  
        }   
    }
    else {
        if(this.connectivity.isOnline()){
            console.log("showing map");
            this.initMap();
            this.enableMap();
        }
        else {
            console.log("disabling map");
            this.disableMap();
        }
    }
  }

    initMap(){
    this.mapInitialised = true;
    navigator.geolocation.getCurrentPosition( (position) => {
        let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        let mapOptions = {
          center: latLng,
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        this.map = new google.maps.Map(document.getElementById("map"), mapOptions);
    }, (error) => {
        console.log(error);
    });
  }
 
  disableMap(){
    console.log("disable map");
  }
 
  enableMap(){
    console.log("enable map");
  }
 
  addConnectivityListeners(){
    var me = this;
    var onOnline = function(){
        setTimeout(function(){
            if(typeof google == "undefined" || typeof google.maps == "undefined"){
                me.loadGoogleMaps();
            } else {
                if(!me.mapInitialised){
                    me.initMap();
                }
                me.enableMap();
            }
        }, 2000);
    };
    var onOffline = function(){
        me.disableMap();
    };
    document.addEventListener('online', onOnline, false);
    document.addEventListener('offline', onOffline, false);
  }

}

app.js:

import {App, Platform} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {TabsPage} from './pages/tabs/tabs';
import {ConnectivityService} from './providers/connectivity-service/connectivity-service';

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [ConnectivityService],
  config: {}
})
export class MyApp {
  static get parameters() {
    return [[Platform]];
  }

  constructor(platform) {
    this.rootPage = TabsPage;

    platform.ready().then(() => {

    });
  }
}

connectivity-service.js:

import {Injectable} from 'angular2/core';
import {Platform} from 'ionic-angular';

@Injectable()
export class ConnectivityService {
  static get parameters(){
    return [[Platform]]
  }  

  constructor(platform) {
    this.platform = platform;
    this.onDevice = this.platform.is('ios') || this.platform.is('android');
  }

  isOnline() {
    if(this.onDevice && navigator.connection){
      let networkState = navigator.connection.type;
      return networkState !== Connection.NONE;
    } else {
      return navigator.onLine;      
    }
  }
 
  isOffline(){
    if(this.onDevice && navigator.connection){
      let networkState = navigator.connection.type;
      return networkState === Connection.NONE;
    } else {
      return !navigator.onLine;     
    }
  }
}

tabs.js:

import {Page} from 'ionic-angular';
import {MapPage} from '../map/map';
import {ListadoPage} from '../listado/listado';

@Page({
  templateUrl: 'build/pages/tabs/tabs.html',
})
export class TabsPage {
  constructor() {
    this.mapPage = MapPage;
    this.listPage = ListadoPage;
  }
}

#2

Dependency Injection is a big thing in angular 2. If you want to inject a service in your current page/component your can decide, if you want to create a new instance of that service or reuse an instance, which is maybe already created in a parent component/page (so you can have something like singletons like in angularjs to share data between app components or you can create multiple instances).

inject a service:

import {Page, NavController} from 'ionic-angular';
import {MyCoolService} from './shared/index';


@Page({
  templateUrl: '...',
  providers: [MyCoolService]
})
export class MyCoolPage {
  constructor(private nav: NavController, private myCoolService: MyCoolService) {}

  myFunction() {
    // this.myCoolService
    // this.nav
  }
}

Now, if you want to share service-instances through your app --> you can add an providers array to your @App decorator like for @Page. But do not add the services again in the @Page decoration --> this creates a new instance!


#3

Hi @bengtler thanks for your reply. So the way I call the service it’ s well done?
I mean already have the providers array in @App and in @Page not. Something else I’m getting an error while I put anything different from a simple parameter in the constructor like this doesn’t work for me:
constructor(private nav: NavController, private myCoolService: MyCoolService)


#4

Thanks for your help @bengtler I knew everithing was right but I forgot to worry about frontend it was the app.core.scss it was empty. Now it’s working sorry for wasting your time. Regards