Angular 5 Learning Experience — Part 3
Service and Dependency Injection
Service is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
Services looks similar to Component. But it got its own Decorator @Injectable() . MetaData for Injectable Declared as below
Note **@Injectable() → denotes otherservice can be inject in to an Service
Basically we are creating a model class and annotating with Injectable decorator and that makes a service
After creating service we need to inject them to component. To do import it in your component which requires it. Then use them part of the component constructor and angular will inject them for you
import { CalendarService } from ‘./calendarService’;
export class CalComponent {
constructor(private calService:CalendarService) {
}
KeyPoints
- If the service injected in AppModule level , then it can be used by all components under it and not above ( top to bottom)
- If the service injected in to Component level, then all child components can use it?
3. Service can be overridden in providers statically as below
providers:[{provide:ActualService,useClass:MockService}]
4. For dynamic override use like below. You need to use a factory. If Factory got dependency , then users deps key
providers:[{provide:ActualService,useFactory:factory}]
ex: factory=(service1,service2) =>{
providers:[{provide:ActualService,useFactory:factory,deps:[service1,service2]}]
}