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");
}
1.)
@InjectableDecorator that marks a class as available to be provided and injected as a dependency. (From: https://angular.io/api/core/Injectable)Means this class can be used with an Injector. But Angular can't actually inject it anywhere until you configure an Angular dependency injector with a provider of that service. This can be done inside of
@Injectable,@NgModule()or@Component()2.) Declaring a service in the providers array of
app.moduleis the same as@Injectable({providedIn: 'root'}). You dont need to do it both. UsingprovidedInis the new / current recommended way of doing it.3.) Service in Angular can be singletons, so if you provide a service in
app.module, you can access the service everywhere and it's always the same instance. If you provide a service on component level, every component-instance get its own instance of the service.is essentially the same as
except that the latter does not use Angular's DI.
4.)
{providedIn: 'root'}, ifprovidedInis not set, the service has to be set via providers-array.5.) Angular DI can't resovle your service. See here: https://stackblitz.com/edit/angular-ivy-c48sfa?file=src/app/app.module.ts