【发布时间】:2019-11-26 22:05:01
【问题描述】:
我的 Ionic 应用程序中有一个组件,它需要屏幕尺寸。在用户更改设备的方向后,我正在尝试使用Platform 插件来获取新的屏幕尺寸。我正在尝试使用以下代码:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnInit, OnDestroy {
deviceWidth: number;
deviceHeight: number;
subs = new Subscription();
constructor(private platform: Platform) {}
ngOnInit() {
subs.add(this.platform.resize.subscribe(async () => {
this.deviceWidth = this.platform.width();
this.deviceHeight = this.platform.height();
console.log(this.platformHeight, this.platformWidth);
});
}
ngOnDestroy() {
this.subs.unsubscribe();
}
}
我遇到的问题是 platform.resize 在动画/过渡到新方向完成之前被调用。因此,platform.height() 和 platform.width() 不正确(它们都被设置为设备的最小尺寸)。为了测试这一点,我为我的 resize 订阅尝试了以下操作:
subs.add(this.platform.resize.subscribe(async () => {
console.log(`Initial Call- width: ${this.platform.width}, height: ${this.platform.height}`);
setTimeout({ // wait until long after the transition animation
console.log(`After Transition- width: ${this.platform.width}, height: ${this.platform.height}`);
}, 1000);
});
在将方向从横向更改为纵向后,会产生以下结果:
Initial Call- width: 414, height: 414
After Transition- width: 414, height: 896
关于如何获得正确的宽度/高度,而不在订阅中插入一些随机的setTimeout,有什么想法吗?
【问题讨论】:
-
尝试用布尔值检查 isResize 条件?