ScreenOrientation using Capacitor on Ionic 5 (Angular)

Hey there!

I follow this documentation to use ScreenOrientation in my app : https://ionicframework.com/docs/native/screen-orientation

First, I installed libraries using this steps :

npm install cordova-plugin-screen-orientation
npm install @ionic-native/screen-orientation
ionic cap sync

Then, in my component.ts file, I just imported it and try to declare in my constructor like this :

import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { IonSlides } from '@ionic/angular';
import { Subscription } from 'rxjs';
import { SliderModel } from './slider.model';
import { HomeService } from '../home.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

@Component({
  selector: 'app-slider-images',
  templateUrl: './slider-images.component.html',
  styleUrls: ['./slider-images.component.scss']
})
export class SliderImagesComponent implements OnInit, OnDestroy {
  
  sliderImgs: SliderModel[];
  private sliderImgsSub : Subscription;

  isLoaded = false;
  
  @ViewChild('slideWithNav2', { static: false }) slideWithNav2: IonSlides;

  sliderTwo: any;
  
  slideOptsTwo = {
    initialSlide: 1,
    slidesPerView: 2.8,
    loop: true,
    autoplay: true,
    centeredSlides: true,
    spaceBetween: 5
  };
  
  constructor(private homeService: HomeService, private screenOrientation: ScreenOrientation) {
    this.sliderTwo =
    {
      isBeginningSlide: true,
      isEndSlide: false,
      slidesItems: []
    };
  }

  ngOnInit() {
    this.sliderImgsSub = this.homeService.fetchImage().subscribe(sliderImages => {
      this.sliderImgs = sliderImages;
      for(let row in this.sliderImgs) {
        const imageUrl = {
          imageB64: this.sliderImgs[row].imageB64,
        };
        this.sliderTwo.slidesItems.push(imageUrl);
      }
      this.isLoaded = true;
    });
  }

  ngOnDestroy() {
    if(this.sliderImgsSub) {
      this.sliderImgsSub.unsubscribe();
    }
  }
}

At this moment, I got a problem, this error message is displayed :

Can't resolve all parameters for SliderImagesComponent in /Users/godaltristan/Desktop/Ionic Development/src/app/home/slider-images/slider-images.component.ts: ([object Object], ?).

I also tried to set ScreenOrientation in providers from my app.module.ts but I got the same error message.

I need ScreenOrientation to update the slidesPerView value in my sliderTwo object when orientation change, but I can’t achieved this.

Tried many solutions on many forums but nothing works.
Does anyone have a solution ?

Thanks.

Have you added it to the app.module.ts…

Hi. Yes, using this way :

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http'
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx'
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    HttpClientModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    ScreenOrientation
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

what code is in home.service…
Instead of:

try

npx cap sync

There is the code in service :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map, tap } from 'rxjs/operators';
import { SliderModel } from './slider-images/slider.model';
import { OracleApexGetRequest } from '../interfaces/oracle-apex-get-request';

@Injectable({
  providedIn: 'root'
})
export class HomeService {

  private _sliderImages = new BehaviorSubject<SliderModel[]>([]);

  get sliderImages() {
    return this._sliderImages.asObservable();
  }

  constructor(private http: HttpClient) { }

  fetchImage() {
    return this.http
    .get<OracleApexGetRequest>(environment.apiUrl + '/home_child_carousel')
    .pipe(map(resData => {
      const sliderImages = [];
      const dataToFetch = resData.items;

      for (const key in dataToFetch) {
        if(dataToFetch.hasOwnProperty(key)) {
          sliderImages.push(new SliderModel(
            dataToFetch[key].imageb64,
            dataToFetch[key].order_news,
            dataToFetch[key].mimetype
          ));
        }
      }
      return sliderImages;
    }),
    tap(sliderImage => {
      this._sliderImages.next(sliderImage);
    }));
  }
}

Tried your command but same error happen.

Thanks.

There is lots of stuff here that i don’t see the reason why…

Where is it being used… because you slider component does not subscribe nor fetch its value… hence i don’t see the need for …

The code above indicates that the API has buried the data that you want within an object. If you have control over the server, return something cleaner so that you avoid having to dig that data out by processing the Observable result with the RxJS map() operator.
If you do that then your fetchimage call can just simply do this…

/** GET images from the server type checked against your slider model */
fetchImages(): Observable<sliderImages[]> {
  return this.http.get<sliderImages[]>(environment.apiUrl + '/home_child_carousel');
}

Then your slider component will expect an array of slider model objects assuming maybe your model looks like…

export interface SliderModel{
 title:string;
 url: string;
.......
}
....

ngOnInit() {
    this.sliderImgs = this.homeService.fetchImage();
  }

Then you can use async pipe (async pipe allows the subscription to observables inside of the angular template syntax. It also takes care of unsubscribing from observables automatically) inside you template to iterate over the images…

<ion-slide *ngFor="let image of sliderImgs | async">
    <img src="{{ image.url }}">
</ion-slide>

Thanks for tips, I use Oracle Apex API so I need to use RxJS, I can’t control how data is coming.

Already trying to make ScreenOrientation working but I got same error, no one got similar problem ?

I’ve added the screenorientation module to a project that am working on for a client and it has no issues.
Create a blank project without anything and try out the module in it. If it runs then remove and add it again in the problematic project.

1 Like

Thanks. Works on another project too. This one is based on a theme. I’ll try with a new one cause “remove and add” don’t change, maybe incompatibility with the theme ?

Works as expected. Thanks.

Nice! Fix! Thank you so much!