如何使用 Ionic 4 检测浏览器和移动网络平台,因为当我在桌面浏览器中尝试使用以下代码时,它没有落入 ‘核心’ 健康)状况。
if (this.platform.is('core')) {
alert('core platform');
} else {
alert('something else');
}
当我在 chrome 开发人员工具中进行调试时,它显示 '机器人' 平台如下图所示。
谁能帮助我如何检测 Ionic 4 中的平台,或者有什么替代方法?
最佳答案
对于我的用例,我想要区分 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';
}
}
}
关于angular - 如何使用 Ionic 4 检测平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51816498/