如何使用Angular 2在NativeScript中获取初始设备方向
我开始使用NativeScript+Angular 2,我想实现一个组件,根据设备方向激活不同的路由。经过大量的搜索,我能够让这个工作,但我还没有找到如何获得初始设备方向,这听起来应该更容易 这是我的如何使用Angular 2在NativeScript中获取初始设备方向,nativescript,angular2-nativescript,Nativescript,Angular2 Nativescript,我开始使用NativeScript+Angular 2,我想实现一个组件,根据设备方向激活不同的路由。经过大量的搜索,我能够让这个工作,但我还没有找到如何获得初始设备方向,这听起来应该更容易 这是我的AppComponent代码。查看ngAfterViewInit: import {Component, OnInit, OnDestroy, AfterViewInit} from "@angular/core"; import {Router} from "@angular/router";
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']);
}
}
}
你可以用。为了获得最新版本的访问权限,您需要每月向维护该版本的开发人员支付订阅费
您可以使用以下方式安装最新的免费版本:
npm i nativescript-orientation
这并不能保证它会工作,特别是在{N}6+中
安装后,您可以获得如下当前屏幕方向:
const orientation = require("nativescript-orientation");
console.log(orientation.getOrientation());
你可以用。为了获得最新版本的访问权限,您需要每月向维护该版本的开发人员支付订阅费
您可以使用以下方式安装最新的免费版本:
npm i nativescript-orientation
这并不能保证它会工作,特别是在{N}6+中
安装后,您可以获得如下当前屏幕方向:
const orientation = require("nativescript-orientation");
console.log(orientation.getOrientation());
虽然据我所知,没有助手来确定初始方向,但您仍然可以获得当前屏幕尺寸。您可以从核心库导入屏幕模块
从“tns核心模块/平台”导入{screen}代码>
然后在应用程序初始化时,通过确定屏幕高度是否大于宽度来确定方向:
this.orientation=screen.mainScreen.heightPixels>screen.mainScreen.widthPixels?”肖像':'风景'代码>
编辑:这可能是不一致的,并且没有完全测试(意味着屏幕高度可能并不总是纵向模式下的屏幕高度)。如果是这种情况,在页面加载时,您可以使用相同的策略来测量主页元素,并比较视图的高度和宽度以确定方向。虽然我知道没有帮助程序来确定初始方向,但您仍然可以获得当前屏幕尺寸。您可以从核心库导入屏幕模块
从“tns核心模块/平台”导入{screen}代码>
然后在应用程序初始化时,通过确定屏幕高度是否大于宽度来确定方向:
this.orientation=screen.mainScreen.heightPixels>screen.mainScreen.widthPixels?”肖像':'风景'代码>
编辑:这可能是不一致的,并且没有完全测试(意味着屏幕高度可能并不总是纵向模式下的屏幕高度)。如果是这种情况,在页面加载时,您可以使用相同的策略测量主页元素并比较视图的高度和宽度以确定方向。这是正确的,但它是特定于Android的。似乎我们错过了一个出口的机会。拉取请求的好机会;)这是正确的,但它是特定于Android的。似乎我们错过了一个出口的机会。拉取请求的好机会;)