How to use .forRoot() within feature modules hierarchy

前端 未结 3 1362
遥遥无期
遥遥无期 2020-12-04 09:51

Can anyone please clarify to me how should I structure multiple nested feature modules hierarchy with .forRoot() calls?

For example what if I have modules like this:

3条回答
  •  一整个雨季
    2020-12-04 10:17

    As mentioned above, lazy loaded modules are important to consider because a shared service could be used in a lazy loaded module, but if that service was already used and instantiated by another module, then there will be two instances hence the need for the singleton pattern. An AuthService is a great example here - you don't want to have one instance of the service with an unauthenticated user while another has "the same" user authenticated.

    New to Angular 6 there is a new way to register a provider as a singleton. Inside the @Injectable() decorator for a service, use the providedIn attribute. Set its value to 'root'. Then you won't need to add it to the providers list of the root module, or in this case you could also set it to your SharedModule like this:

    @Injectable({
      providedIn: SharedModule // or 'root' for singleton
    })
    export class AuthService {
    ...
    

提交回复
热议问题