离子 4 - 屏幕方向(横向)不起作用



我是 Ionic 4 的新手,我正在尝试将屏幕方向设置为横向并参考文档,这就是我正在做的事情:

...
import {ScreenOrientation} from '@ionic-native/screen-orientation';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private screenOrientation: ScreenOrientation,
  ) {
    this.initializeApp();
  }
  initializeApp() {
    this.screenOrientation.lock(ScreenOrientation.ORIENTATIONS.LANDSCAPE);
    ...
  }
}

在编译过程中,我收到此错误:

[ng] src/app/app.component.ts(24,33) 中的错误:错误 TS2345:类型"字符串"的参数不可分配给类型为"OrientationLockType"的参数。

在浏览器控制台上:

未捕获的错误:无法解析 AppComponent 的所有参数:([对象对象]、[对象对象]、[对象对象]、?)。 at 语法错误 (编译器.js:2426) [] ...

您使用 ionic V4,请参阅文档,导入正确的东西。

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

import {ScreenOrientation} from '@ionic-native/screen-orientation';

第四个参数的注入存在问题,是否正确安装了屏幕方向插件?

ionic cordova plugin add cordova-plugin-screen-orientation
npm install @ionic-native/screen-orientation

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-screen-orientation/

如果这不起作用,您应该尝试这种方式(无需导入和注入)

cordova plugin add cordova-plugin-screen-orientation

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-screen-orientation/

此外,如果您想为整个应用程序强制横向,可以在配置中添加首选项.xml

<preference name="orientation" value="landscape" />

我已经测试过它,它可以在安卓平台 7.1.4 中运行

确保使用插件将ScreenOrientation添加到模块中的提供程序数组中。

例如在app.module.ts

使用插件的模块中的提供程序数组。

    providers: [
    ScreenOrientation
 ]
这对

我有用(Ionic 5)。在你的页面模块中,导入依赖项:

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

并向模块提供:

 providers: [
    ScreenOrientation, 
    ...]

最新更新