Using Provider as Singleton

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

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”

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

what does that mean?

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

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.

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

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();
   }
}
1 Like