如何判断我是否在使用 Ionic2 的移动平台上?

How to tell if I am on a mobile platform with Ionic2?

我开始学习 ionic2 以加快我的开发过程。 我的主要关注点是网络,移动是额外的好处。我已经设法调整 ionic2 gulpfile 以便从 golang 后端提供服务。一切都很好,但我需要一种方法来确定我是在 Android 还是 ios 上,以便更改域位置我的 api 正在发送请求 for.Eg:

在开发我的应用程序时服务于 localhost:8080 所以 document.location.hostname 将 return 本地主机,我将能够向 localhost:8080/api/endpoint

发出请求

在生产中,我的应用程序在 www.wonderfulapp.com 上运行,所以 document.location.hostname 会 return www.wonderfulapp.com 并且我可以向 www.wonderfulapp.com /api/endpoint

发出请求

我希望我的代码确保我在从 android 和 ios 发出请求时使用 www.wonderfulapp.com。我该怎么做?

您需要按如下所述注入 Platform class:

import {Platform} from 'ionic-angular';

@Page({...})
export class MyPage {
  constructor(platform: Platform) {
  }
}

或者像这样使用 ES6:

@Page({...})
export class MyPage {
  constructor(platform) {
  }

  static get parameters() {
    return [[Platform]];
  }
}

Platform class 有一个 is 方法来检查目标平台。如果要检查特定设备,可以使用以下值作为此方法的参数:

  • mobileweb 在移动设备的浏览器中。
  • mobile 在移动设备上。
  • android 在设备上 运行 Android.
  • ios 在设备上 运行 iOS.

这是一个示例:

@Page({...})
export class MyPage {
  constructor(platform: Platform) {
    if (platform.is('mobileweb')) {
      // Do something
    }
  }
}

有关详细信息,请参阅此文档: