10

I understand there have been some changes in Angular 6 with the way singleton services have to be created. I have an Auth Service that needs to be constructed once for each component that accesses it. I set the provider to root for the service:

@Injectable({
  providedIn: 'root'
})

And in my app.module.ts file, I set AuthService as one of my providers in NgModule. However, whenever I route between different components that use the Auth service, it creates a new instance of the Auth Service (clearing data from the first time it was called). How do I ensure that the Auth Service is only instantiated once, and then access that instance among different components?

2 Answers 2

7

That's the default behaviour of adding providedIn to the service level. As per Docs

providedIn here tells Angular that the root injector is responsible for creating an instance of the HeroService. Services that are provided this way are automatically made available to the entire application and don't need to be listed in any module.

in your case just remove the providedIn: 'root' and have only under provides in the module.ts. Refer the following answer.

Sign up to request clarification or add additional context in comments.

7 Comments

I see. I do not understand how to then instantiate a global instance of the Auth service then. I get this error: Uncaught Error: Can't resolve all parameters for AuthService: (?).
IMPORTS GO HERE @Injectable() export class AuthService { user: any; constructor(private fireBaseAuth: AngularFireAuth) { this.fireBaseAuth.authState.subscribe(user => { if(user){ console.log(user) this.user = user }else{ this.user = undefined } }); } userDetails(){ if(this.user){ return this.user; } else{ return undefined } } isLoggedIn(){ console.log(this.user) if(this.user){ return true } else{ return false } } }
post in your code and the app.module.ts in the question
no when you refresh the page it will be instantiated again , yes you should go for a session storage
|
4

To avoid any other confusion you can create singletons in two ways, just as stated in the docs (singleton-services):

  • Declare that the service should be provided in the application root.
    @Injectable({providedIn: 'root'}).
    The service should not be imported in any module then.
  • Include the service in the AppModule or in a module that is only imported by the AppModule.
    Here no need to use {providedIn:'root'}.

In my case singleton services did not work when using JIT (normal ng build / ng serve). For me it only worked when using AoT (ng build --aot / ng serve --aot).

1 Comment

Same Problem in Angular 8. it is not working without aot flag. I had wasted 2-3 days for this simple flag. Why it does not work without aot?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.