I am learning about Injectables and Services in Angular and I am not clear about certain importing and default characteristics about injectables. Specifically, when should a service in Angular:
Have the @Injectables tag? I had seen a blogpost that doesn't use it. What happens when you leave it out, and how would leaving this tag being left out change the way the service behaves?
Be declared in the providers array in app.module?
Be declared in the providers array of an individual component, rather than the app.module?
What is the default value of the providedIn keyword when using the @Injectables tag? If this keyword is not defined in your service, what should be assumed about the keyword's value and the service's scope?
Say I have a service (let's call it
DummyService
) with these characteristics: has the @Injectables tag, does not define providedIn, is not declared in any providers array (neither app.module nor any individual component).- 5.a) Since providedIn was not specified and the service is not declared in any providers array, can this service be shared with sibling components?
- 5.b) When calling DummyService from a component who imported DummyService, what is the difference from these use cases:
DummyService.addToList("Stacy");
vs
constructor(private _dummyservice: DummyService){}
ngOnInit(){
this.dummyservice.addToList("Stacy");
}
The code above tells angular, take this class and load it to the injector/container which can be thought as a container on top of the components. Angular will automatically create a single instance of each service for us. We do not create ourselves like
angular will make it for us and make it available to all the different components inside the injector container. this will make the code reusable.
So whenever someone calls
DummyService
in any component, angular will ship the instance of DummyService. You could manually create it in the constructor of your component class.if you go to browser and check the compiler, get to the line where your class is defined you will see something like this:
All the code inside of the typescript files are being processed by the typescript compiler before it even gets executed inside the browser. then webpack takes over, all those types, all those annotations, all the public and private stuff gets ripped out. As your browser does not know how to understand typescript. Class components constructor arguments also ripped out as a new property like above.