Using services with components

We will now evolve Example2 once again and refactor some of the code that was defined at the component level into an Angular service.

A service is a TypeScript class that has a decorator called Injectable without any parameters that allows the service to be part of the dependency injection (DI) mechanism in Angular 2. DI will ensure that a service instance will be created only once per application, and this instance will be injected in any class that declares it as a dependency in their constructor declarations. Apart from the specific decorator, a service needs to be declared as a provider usually in a module definition, but it can also be declared in component, directive, or pipe definitions. Before jumping ...

Get Expert Angular now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.