【问题标题】:How to always check if the Location service is enabled in Ionic 2?如何始终检查 Ionic 2 中是否启用了位置服务?
【发布时间】:2017-08-03 14:23:38
【问题描述】:

我试图弄清楚如何始终检查位置服务是否已启用。总是我的意思是像一个实时检查器。我现在所拥有的只是一种观点。我正在检查用户何时登录 - 如果启用了位置服务,他会登录。但是,如果未启用,则会出现一个警报对话框:

这是我检查它是否启用的函数:

 checkLocation() {
    this.diagnostic.isLocationEnabled().then(
      (isAvailable) => {
        console.log('Is available? ' + isAvailable);
        if (isAvailable) {
          this.navCtrl.setRoot(UserTypePage);
        } else {
          alert('Please turn on the location service');
          if (this.autoLogin) {
            this.autoLogin();
          }
        }
      }).catch((e) => {
        console.log(e);
        alert(JSON.stringify(e));
      });
  }

当用户尝试登录时,我会调用此函数。

Facebook 登录示例:

facebookLogin(): void {
    this.global = ShareService.getInstance();
    this.subscriptions.push(this.authProvider.loginWithFacebook().subscribe((user) => {
      this.loading.dismiss().then(() => {

        this.global.setUserName(user.displayName); 
        this.global.setProfilePicture(user.photoURL);
        this.global.setUserId(this.authProvider.currentUserId);
        this.tokenstore();
        this.checkLocation(); //HERE
      })

    }, error => {
      this.loading.dismiss().then(() => {
        let alert = this.alertCtrl.create({
          message: error.message,
          buttons: [
            {
              text: "Ok",
              role: 'cancel'
            }
          ]
        });
        alert.present();
      });
    }, (err) => {
      console.error("error: " + JSON.stringify(err));
    }));
    this.loading = this.loadingCtrl.create({
      content: 'Signing in...'
    });
    this.loading.present();
  }

我希望这个功能可以在整个应用程序中工作,而不仅仅是在登录视图中。我该怎么做?

【问题讨论】:

    标签: ionic-framework ionic2


    【解决方案1】:

    这是一个经典场景,Angular Dependency Injection 将帮助您跨组件/视图重用现有方法。

    您可以在您的应用程序中创建一个 LocationCommonService 并定义方法来检查位置服务是否已启用。

    现在在所有需要调用所需函数的组件中注入LocationCommonService。

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 2014-08-22
      • 2016-04-24
      • 2019-01-21
      • 2015-12-02
      • 2016-08-15
      相关资源
      最近更新 更多