[Solved] Problem with NativeStorage in ionic 4

Hi everyone,
I have a problem with NativeStorage in ionic 4.
I have a service looks like:

import { Injectable, OnInit, OnDestroy } from '@angular/core';
import { NativeStorage } from '@ionic-native/native-storage/ngx';

@Injectable({
  providedIn: 'root'
})
export class FavoriteStoreService implements OnInit, OnDestroy {

  favorites: Array<any> = new Array<any>();

  key: string = "favorites";

  public addFavorite(favorite: any) {
    this.favorites.push(favorite);
    this.save();
  }

  public getFavorites() {
    return this.favorites;
  }

  private save() {
    // TODO:
  }

  private load() {
    // TODO:
  }

  constructor(private nativeStorage: NativeStorage) {
  }

  ngOnInit() {
    this.load(); 
  }

  ngOnDestroy() {
    this.save();
  }
}

The service is used in a page looks like:

import { FavoriteStoreService } from './../services/favorite-store.service';
import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';


@Component({
  selector: 'app-favorite-input',
  templateUrl: './favorite-input.page.html',
  styleUrls: ['./favorite-input.page.scss'],
})
export class FavoriteInputPage implements OnInit {

  value;
  formData: FormGroup;

  constructor(private modalCtrl: ModalController, private formBuilder: FormBuilder, private favoriteStore: FavoriteStoreService) { 
    this.formData = this.formBuilder.group({
      comments: ['', Validators.compose([Validators.minLength(3), Validators.required])]
    });
  }

  ngOnInit() {
  }

  ionViewDidLoad(){
  }

  dismiss() {
    this.modalCtrl.dismiss();
  }

  public save() {
    let favorite = {
      "imdbID": this.value.imdbID,
      "comment": this.formData.value.comments
    };
    this.favoriteStore.addFavorite(favorite);
  }
}

The problem is the page is blank after loaded, the content of the page isn’t shown. If I remove the injection of NativeStorage in constructor of FavoriteStoreService then everything is fine, the content of the FavoriteInputPage is shown.

Can someone help me please?

I found the problem, the console.logs of Firefox didn’t show the specific error. Google Chrome is better, the actual problem is NullInjectorError: No provider for NativeStorage!, so I just added NaviteStoragein providers of app.module.ts and the problem is solved.

1 Like

Incidentally, lose the lifecycle handlers in your service. They are only relevant for components and directives.