Error when subscribing to Screen Orientation changes

I am trying to use cordova’s ScreenOrientation module to get screen orientation changes. Using their example online, I’ve written this code in my app.component.ts:

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private so: ScreenOrientation,
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      console.log('orientation is', this.so.type);
      this.so.onChange().subscribe(() => {
        console.log('orientation changed to ', this.so.type);
      });
    });
  }

}

When I run my app – and this is a brand new ionic project with no other changes – I see this error in the logs:

ERROR TypeError: Invalid event target
    at setupSubscription (fromEvent.js:50)
    at Observable._subscribe (fromEvent.js:24)
    at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43)
    at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29)
    at app.component.ts:28
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:17299)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
defaultErrorLogger @ core.js:15724

Does anyone know what this means and how to fix it? My subscriptions to the onChange events do not work, so I’m not getting the orientation changes.

(This is Ionic 4.)

Hi @VictorNorman,

I did have the same problem and resolved using “javascript” with handling of event “orientationchange”.

I used into my component.ts

declare var window: any;

ionViewWillEnter() {
   window.addEventListener('orientationchange', _ => {
      console.log('Change orientation.')
   });
}

ionViewWillLeave() {
    window.removeEventListener('orientationchange');
}

i hope that solve your problem too

1 Like

Thank you very much!

1 Like