Using Provider as Singleton


#1

Hi
How to use a provider for saving login data as singleton ?


#2

As long as you declare your providers for your all app in providers of your app.module.ts, providers are singletons

Src: https://angular.io/guide/dependency-injection
See chapter “Singleton services”


#3

And after declare it in app.module.ts i don’t need to declare it on a page ?


#4

what does that mean?


#5

I don’t have to import my provider again in a page ?


#6

You need to import it and declare in the constructor so the singleton gets injected

See https://angular.io/guide/dependency-injection

As earlier mentioned.


#7

Hi

and may I suggest you to run a new project using the conference app, and then study this code? Pretty sure it gives all the guidance you are looking for!

ionic start

then select conference

Regads

tom


#8

pseudo code ->

app.module.ts

@NgModule({
   ....
   providers: [
        YourSingletonProvider,
        AnotherOne
   ]

in any pages:

 import {YourSingletonProvider} from './providers/your-singleton-provider';
...
 export class WhaterverPage {
 
     constructor(private yourSingletonProvider: YourSingletonProvider) {
     }
  
   something() {
       this.yourSingletonProvider.whatever();
   }
}