@Injectable() decorator and providers array

前端 未结 2 1236
暗喜
暗喜 2021-01-17 04:38

Does a service that is provided in \"root\" within the @Injectable() decorator still have to be in the providers array of the module?

The Angular documentation doesn

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 05:18

    Does a service that is provided in "root" within the @Injectable() decorator still have to be in the providers array of the module?

    No!

    When you create a service with the Angular CLI I believe that the providedIn: "root" is added by default, so technically you do not ever need to add one of your own services into a providers array.

    Do I have to additionally set up the service in the providers array of the module, or is it enough that it is already provided at root level using the decorator?

    It should be enough that it is provided at the root level using the decorator.

    However, not all of the services I create are intended to be global. It is not uncommon for me to remove the configuration object to the @Injectable()metadata when I am creating a service that will be shared among a single screen or sub module--not across the full application.In such a case I will have to add that service to a providers array on the respective components that use it or sub module declaration.

提交回复
热议问题