使用 Ionic3 时出现不支持错误

Getting Not Supported Error while using Ionic3

我绞尽脑汁能够捕捉到这个错误。 在桌面上时,此代码引发此 NotSupportedError:

我通常在 chrome 上调试。

代码如下:

import {Component} from "@angular/core";
import {ScreenOrientation} from "@ionic-native/screen-orientation";

@IonicPage()
@Component({
  selector: 'page-loading',
  templateUrl: 'page-loading.html',
})
export class PageLoading {

  constructor(private screenOrientation:ScreenOrientation) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad PageLoading');

    try{
        this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT).then(()=>{
          console.log('lock');
        });
    }catch(e){
      console.warn('No cordova.js')
    }

  }

}

您可以创建一个 class 来模拟 ionic native classes,如文档 here.

中所述
class ScreenOrientationMock extends ScreenOrientation {
  lock(type) {
    return new Promise((resolve, reject) => {
      resolve("locked");
    })
  }
}

ngModule 的供应商列表中提到它应该使用你的模拟 class 而不是实际的离子本机。

providers: [..
    { provide: ScreenOrientation, useClass: ScreenOrientationMock }
 ]

这将 return 您在 resolve 中为 ionic serve 期间设置的屏幕方向。

一旦它 运行 在设备中,您就可以将其删除。

编辑:

还有一种方法可以抑制你的错误,这样你最后就无事可做了:

if(this.platform.is('cordova')){
  this.platform.ready().then(()=>{
   this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  })
}