如何使用Ionic 4检测平台 [英] How to detect platform using Ionic 4

查看:226
本文介绍了如何使用Ionic 4检测平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Ionic 4检测浏览器和移动网络平台,因为当我在台式机浏览器中尝试以下代码时,它并没有处于核心" 状态.

How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }

当我在chrome开发人员工具中进行调试时,它会按照下面的快照显示'android'平台.

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

任何人都可以帮助我如何在Ionic 4中检测平台吗?或者有什么替代方法?

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

推荐答案

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

For my use case I wanted something to distinguish between native and browser platforms. That is, is my app running in a browser or a native mobile device. Here's the service I came up with:

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

这篇关于如何使用Ionic 4检测平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆