【问题标题】:How to get the initial device orientation in NativeScript with Angular 2如何使用 Angular 2 在 NativeScript 中获取初始设备方向
【发布时间】:2016-09-30 21:27:08
【问题描述】:

我开始使用 NativeScript + Angular 2,我想实现一个组件,根据设备方向激活不同的路由。经过大量搜索,我能够得到这个工作,但我还没有弄清楚如何获得 initial 设备方向,这听起来应该更容易。

这是我的AppComponent 代码。看ngAfterViewInit

import {Component, OnInit, OnDestroy, AfterViewInit} from "@angular/core";
import {Router} from "@angular/router";

import _application = require('application');

@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
    constructor(private router: Router) {}

    ngOnInit() {
        _application.on(_application.orientationChangedEvent, this.setOrientation.bind(this));
    }

    ngAfterViewInit() {
        // How do I get the initial orientation here instead of hardcoding to 'portrait'?
        this.setOrientation({newValue: 'portrait'})
    }

    ngOnDestroy() {
        _application.off(_application.orientationChangedEvent, this.setOrientation);
    }

    setOrientation(args) {
        if (args.newValue === 'landscape') {
            this.router.navigate(['/landscape']);
        } else {
            this.router.navigate(['/portrait']);
        }
    }
}

【问题讨论】:

    标签: nativescript angular2-nativescript


    【解决方案1】:
    private activity:any = application.android.foregroundActivity;
    this.activity.getResources().getConfiguration().orientation;
    

    【讨论】:

    • 这是正确的,但它是特定于 Android 的。似乎我们错过了为此导出API。一个拉取请求的好机会;)
    【解决方案2】:

    您可以使用this plugin。为了获得最新版本的访问权限,您需要每月向维护ProPlugins 的开发人员支付订阅费用。

    您可以使用以下命令安装它的最后一个免费版本:

    npm i nativescript-orientation
    

    这并不能保证它会起作用,尤其是在 {N} 6+ 中。

    安装后,您可以像这样获取当前屏幕方向:

    const orientation = require("nativescript-orientation");
    console.log(orientation.getOrientation());
    

    【讨论】:

      【解决方案3】:

      虽然没有帮助确定我所知道的初始方向,但您仍然可以获得当前的屏幕尺寸。您可以从核心库中导入 screen 模块。

      import { screen } from 'tns-core-modules/platform';

      然后在应用程序初始化时通过确定屏幕高度是否大于宽度来确定方向:

      this.orientation = screen.mainScreen.heightPixels > screen.mainScreen.widthPixels ? 'portrait' : 'landscape';

      编辑:这可能不一致并且没有经过全面测试(这意味着屏幕高度可能并不总是纵向模式下的屏幕高度)。如果是这种情况,在页面加载时,您可以使用相同的策略来测量主要页面元素并比较视图的高度和宽度以确定方向。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多