首页 > 解决方案 > 如何使用 Ionic 4 检测平台

问题描述

标签: angulartypescriptionic-frameworkionic4platform

解决方案


对于我的用例,我想要一些东西来区分nativebrowser平台。也就是说,我的应用程序是在浏览器中运行还是在本机移动设备中运行。这是我想出的服务:

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


type CurrentPlatform = 'browser' | 'native';

@Injectable({
  providedIn: 'root'
})
export class CurrentPlatformService {

  private _currentPlatform: CurrentPlatform;

  constructor(private platform: Platform) {
    this.setCurrentPlatform();
  }

  get currentPlatform() {
    return this._currentPlatform;
  }

  isNative() {
    return this._currentPlatform === 'native';
  }
  isBrowser() {
    return this._currentPlatform === 'browser';
  }

  private setCurrentPlatform() {
    // Are we on mobile platform? Yes if platform is ios or android, but not desktop or mobileweb, no otherwise
    if (
        this.platform.is('ios')
        || this.platform.is('android')
        && !( this.platform.is('desktop') || this.platform.is('mobileweb') ) ) {
      this._currentPlatform = 'mobile';
    } else {
      this._currentPlatform = 'browser';
    }
  }
}

推荐阅读