DEV Community


Posted on

Angular Services

Hey guys can someone recommend a simple fullstack explanation of what #angular services are. I realize for a fact that they are key in sharing data between multiple components, is there any key thing about services other than that?

Top comments (2)

bradtaniguchi profile image

One of Angular's key features is its dependency injection system. This allows components/directives/pipes/services/etc to "inject" dependencies, thus giving the developer the ability to share code and test easily, among other things.

One use of the DI system is using services which are usually nothing more than a class with the @Injectable decorator. Once you provide the service from somewhere, like in a module or component, Angular knows where it will be "provided from". It uses this information to determine what module to bundle the service with (like in a lazy module). Often you just want 1 service across the entire app and can provide it from the app.module, or use the @Injectable({providedIn: 'root'}) syntax (available after ng6) to have Angular figure out where to provide it from (this is usually the recommended approach). There are a number of different approaches that can be taken on how to "provide" something in Angular that opens up a ton of doors.

Regardless of where the service is provided, Angular will automatically create an instance when required. (or not even include the service in the final bundle if it isn't used)

Once the class "asking" for the service get's it, its just like any other class instance. So you can throw in utility functions, business logic, shared state, message passing (as you pointed out), and interchangeable implementations. During testing you can "mock" or "stub" out the service, so they can act as an "interface" where you can mock complex functionality away during testing.

Optimally you put most of your apps logic in a service so its easier to test (no template to deal with) re-use and use, leaving components to do as little as possible when it comes to business logic.

The DI pattern is used in other technologies like Spring for Java, so its a tried and true approach, even if it seems verbose and unnecessary for simpler use-cases.

Services are only part of the "key idea" of Angular's DI system. Good examples are being able to swap out entire functionality by providing different interfaces for different build targets, and customizing the entire application by providing injection tokens to override defaults, and at different levels override the overrides haha.

DI is super powerful for a lot of use-cases, but services themselves are just classes provided through it. Learn how to leverage the DI system and services become more powerful :)

nyalikmarvin profile image

Talking about angular services and dependency injection i think this is the best guide for a beginner. Find it here