ค้นหาเว็บไซต์

angular - วิธีตรวจสอบแพลตฟอร์มโดยใช้ Ionic 4


วิธีตรวจจับแพลตฟอร์มเบราว์เซอร์และเว็บมือถือโดยใช้ Ionic 4 เพราะเมื่อฉันลองใช้โค้ดด้านล่างในเบราว์เซอร์เดสก์ท็อป มันไม่ตรงตามเงื่อนไข ‘core’

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

เมื่อฉันทำการดีบักในเครื่องมือสำหรับนักพัฒนาของ Chrome มันจะแสดงแพลตฟอร์ม 'android' ดังตัวอย่างภาพด้านล่าง

มีใครช่วยฉันได้บ้างว่าจะตรวจสอบแพลตฟอร์มใน Ionic 4 ได้อย่างไร หรือมีทางเลือกอื่นสำหรับสิ่งนี้ไหม?

คำตอบ #1

สำหรับกรณีการใช้งานของผม ผมต้องการสิ่งที่สามารถแยกความแตกต่างระหว่างแพลตฟอร์ม native และ browser นั่นคือ แอปของผมกำลังรันในเบราว์เซอร์หรือบนอุปกรณ์มือถือแบบ native นี่คือบริการที่ผมคิดขึ้นมา:

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

คำตอบ #2

ปัจจุบัน Ionic 4 มีการสนับสนุนการตรวจจับแพลตฟอร์ม โค้ดต่อไปนี้ใช้งานได้สำหรับฉัน

import { Platform } from '@ionic/angular';
...
constructor(private platform: Platform) {}
...
ngOnInit() {
   this.platform.ready().then(() => {
      if (this.platform.is('android')) {
           console.log('android');
      } else if (this.platform.is('ios')) {
           console.log('ios');
      } else {
           //fallback to browser APIs or
           console.log('The platform is not supported');
             }
      }}

บทความที่เกี่ยวข้อง