【问题标题】:injecting service into tabs ionic 2将服务注入标签离子2
【发布时间】:2016-05-09 01:38:35
【问题描述】:

我正在关注本教程advanced google maps component in ionic 2
我一步一步地做到了,而且效果很好,但只在单页中。 在我的项目中,我打算使用选项卡或侧边菜单设计。
我已经在本教程的博客上询问过,但仍然没有回复。
提前感谢任何帮助或建议。
我在控制台中尝试了以下操作,没有出现错误。
map.js:

import {Page, NavController} from 'ionic-angular';
import {ConnectivityService} from '../../providers/connectivity-service/connectivity-service';
@Page({
  templateUrl: 'build/pages/map/map.html',
  providers: [ConnectivityService],
})
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");
            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);
  }
}`


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;     
    }
  }
}


app.js

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


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
  static get parameters() {
    return [[Platform]];
  }

  constructor(platform) {
    this.rootPage = TabsPage;

    platform.ready().then(() => {
      StatusBar.styleDefault();
    });
  }
}


tabs.html:

<ion-tabs>
  <ion-tab [root]="mapPage" tabIcon="map"></ion-tab>
  <ion-tab [root]="listPage" tabIcon="list-box"></ion-tab>
</ion-tabs>


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;
  }
}

【问题讨论】:

  • 你有 tabs.html 吗?
  • 注入您遇到的实际问题是什么?
  • 嗨 @wilburrr90 是的,我有它,所以 tabs.js 你想让我发布它吗?
  • 嗨@GünterZöchbauer 问题我认为如果服务的注入做得很好。在一个单页项目中,它就像我提到的那样工作,我从以下位置获取了这个实现:www.joshmorony.com/creating-an-advanced-google-maps-component-in-ionic-2

标签: javascript google-maps-api-3 angular ionic2


【解决方案1】:

您拥有正确的架构,它也适用于菜单或选项卡或许多不同的页面; sidemenu 或 tabs 只是显示页面的一种方式。

如果您担心从菜单或选项卡模板本身访问服务,请记住它们只是 @App 类的关联模板。因此,要从他们那里访问服务,您需要将服务添加到 @Appconstructor,就像您为 @Page 所做的一样(您现在没有这样做)。

【讨论】:

  • 嗨@Manu Valdés 我试过你说的,结果还是一样,它根本不起作用。 constructor(platform,connectivityService){this.rootPage = TabsPage;this.connectivity = connectivityService;platform.ready().then(() =&gt; {});}
  • 我认为您需要描述什么不起作用。似乎您实际上并不需要从侧面菜单或选项卡访问服务,因此您可以从 @App 提供程序和构造函数中删除 ConnectivityService 。只需将其留在 MapPage 上即可。接下来,您确实意识到您的“@App”将加载 TabsPage,而不是 MapPage?只是为了确保,向我们展示您的 TabsPage 模板,它应该有一个指向 MapPage 的 ion-tab,如下所示:
  • 嗨@Manu Valdés 我试过你说的,结果还是一样,它在所有地图页面上都不起作用。我按照您的要求发布了标签模板,并从 app.js 中删除了该服务。并且错误仍然是“Google maps JavaScript需要加载”这个错误来自map.js。
  • 这不是错误消息,它让我们知道它将加载地图 js。你收到其他消息了吗?您可以发布到控制台和服务器日志吗? (您可以使用 c 和 s 命令在 ionic serve 中激活它们)
  • 我知道这确实不是错误消息。但它仍然失败,当我在单个页面中使用它时,同样的代码不会失败。这是控制台日志:Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode. 1 221201 log Google maps JavaScript needs to be loaded. 2 221209 log disable map 3 221217 log online, loading map 4 221485 log enable map 5 227437 warn Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
【解决方案2】:

我认为您在地图组件中忘记了providers:[...]

【讨论】:

  • 嗨@qchap 你指的是这个:[ConnectivityService] 这就是它命名提供者的方式。你认为它在哪里丢失了?
  • 在您的@page 内是的
  • 我已经尝试过这样做,包括 map.js 上的提供程序,但它没有改变。我真诚地尝试了很多组合。 @Page({ templateUrl: 'build/pages/map/map.html', providers: [ConnectivityService], })
猜你喜欢
  • 2017-08-24
  • 2017-10-15
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多