0

I'm developing an Ionic 4 app based on Angular 7 and want to create a service that provides to the whole app as a singleton instance.

According to the newest version of docs of Angular 7 you dont need to specify the service in the providers section of app.module.ts, you can easily just annotate the service with the providedIn: 'root' annotation and then just inject it in the components/pages.

service file:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

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

  constructor(public storage: Storage) {}
  ...
}

And then i just inject it into my components constructor like this:

import { StorageService } from '../services/storage.service';

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

  constructor(private storage: StorageService) { }

  ngOnInit() {}
  ...
}

But when i launch my app i get this error:

Uncaught (in promise): Error: StaticInjectorError(AppModule)[Storage]: 
  StaticInjectorError(Platform: core)[Storage]: 
    NullInjectorError: No provider for Storage!
main.c
  • 169
  • 2
  • 15

1 Answers1

1

In the main module, replaces IonicStorageModule by IonicStorageModule.forRoot()

 imports: [
      IonicStorageModule.forRoot() 
 ]
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80