Skip to main content

Services

Contents

Usage

@Injectable

  • Used for dependency injection

  • services defined in AppModule have application level scope

  • Use providedIn in the service itself to make it have application level scope

    @Injectable({
// makes the services available application-wide
providedIn: 'root'
})

Dependency Injection

Create same instance of a single @Injectable class instead of creating them in every component

  • Create a service
TestService
    // make the file a service
@Injectable({})
// function
calculate(){}
// export
export class TestService()
  • Expose the service to Angular's Dependency Injection
AppModule
    providers : [
TestService
]
  • Use it in components
TestComponent
    constructor(
private testService: TestService
){}

this.testService.calculate();

Injection Tree

  • If we add TestService Injectable to component each instance of component receives separate instance of TestService
  • But nested components receive same instance as their parent component
ParentComponent
    @Component({
selector : 'parent',
templateUrl : './parent.component.html',
styleUrls : ['./parent.component.css'],
// provide service in a component
providers: [TestService]
})