Angular Services and Dependency Injection
For data or logic that is not associated with a specific view, and that you want to share across components, you create a service class. A service class definition is immediately preceded by the @Injectable
decorator. The decorator provides the metadata that allows your service to be injected into client components as a dependency.
Dependency injection (or DI) lets you keep your component classes lean and efficient. They don’t fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.
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.
Angular distinguishes components from services in order to increase modularity and reusability.
- By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient. Ideally, a component’s job is to enable the user experience and nothing more. It should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).
- A component should not need to define things like how to fetch data from the server, validate user input, or log directly to the console. Instead, it can delegate such tasks to services. By defining that kind of processing task in an injectable service class, you make it available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.
Angular doesn’t enforce these principles. Angular does help you follow these principles by making it easy to factor your application logic into services and make those services available to components through dependency injection.
IT Professionals, Web Developers, Web Programmers, IT students can Apply for the certification course to move ahead in their careers.