gargara123456
gargara123456

Reputation: 299

Why you need to provide service in module

I am building an Angular app and I have a module and a service class that is holding all my needed functions. I am importing the service class in my component and I use it as needed. Now I see that I need to include it into the module providers. But why is this needed? I am already using it as it is and including it into the module providers do not change nothing in the way I am using it. I still need to import it and declare an instance of it in the component. What is the difference?

Upvotes: 2

Views: 2609

Answers (2)

gargara123456
gargara123456

Reputation: 299

To answer my question if someone else is wondering the same. The reason the services to work without declaring them in providers is because the Injectable that Angular adds automatically when the services is created with ng generate service:

@Injectable({
providedIn: 'root'
})

I suppose if it is not there then the providing will be necessary.

Upvotes: 2

Melvin Kah Hoo
Melvin Kah Hoo

Reputation: 196

Service need to be declare in the module provider to tell Angular to include the service class in your module. When you project is more complex, you will have more modules in a single project. So you will want to import only the relevant code into your module. Thus you can choose only a specific set of services you want to in the providers.

Else you can also declare the service as root service. By doing sos, you can use the service everywhere within your project without declaring in the provider.

Upvotes: 3

Related Questions