CESCO
CESCO

Reputation: 7768

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

I started learning ionic2 to speed up my development process. My primary focus is the web, Mobile is a bonus. I have managed to tweak ionic2 gulpfile in order to it be served from a golang backend. It all works very well, but I need a way to tell for sure whether I am on Android or ios in order to change the domain location my api is sending request for.Eg:

While developing my app serves at localhost:8080 so document.location.hostname would return localhost and I would be able to fire a request to localhost:8080/api/endpoint

In production my app serves at www.wonderfulapp.com so document.location.hostname would return www.wonderfulapp.com and I would be able to fire a request to www.wonderfulapp.com /api/endpoint

I want my code to make sure I user www.wonderfulapp.com when firing request from android and ios. How do I do that?

Upvotes: 1

Views: 158

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202196

You need to inject the Platform class as described below:

import {Platform} from 'ionic-angular';

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

or like this with ES6:

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

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

The Platform class has a is method to check the target platform. If you want to check that a particular device, you can use the following values as parameter of this method:

  • mobileweb in a browser on a mobile device.
  • mobile on a mobile device.
  • android on a device running Android.
  • ios on a device running iOS.

Here is a sample:

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

See this doc for more details:

Upvotes: 1

Related Questions