Angular Fundamentals: Creating Reusable Angular Services

Kevin O'Shaughnessy
2 min readAug 6, 2019

--

Welcome back to this review of the Pluralsight course Angular Fundamentals by Joe Eames and Jim Cooper.

The previous episodes have covered each of earlier modules in this course:

This is a short module explaining Angular Services.

Why We Need Services and Dependency Injection

Our Events List component is currently responsible for too many things.

The responsibility for defining and supplying event data should be moved out into an Angular service. Jim discusses injecting a service into a component’s constructor method.

Creating Your First Service

Jim creates a new file event.service.ts

We inject Angular’s HTTP service into the event service constructor, and apply the @Injectable decorator to the class.

We need to remember to add our service to the app.module.ts file, and add it as a provider in the @NgModule definition.

Jim also introduces the OnInit lifecycle hook method (this is also covered in Deborah Kurata’s Angular: Getting Started course).

We can also leverage TypeScript’s support for interfaces, by declaring that we our new service implements OnInit. This helps protect us against making accidental breaking changes in the future, due to the TypeScript compiler.

Try the practice exercise.

Wrapping Third Party Services

In this clip, Jim uses toastr to display success notifications when we click on an event.

Once this is working, he notes a couple of problems with the implementation:

  1. We’re reusing toastr as a global object
  2. Its not testable because we can’t mock it

So Jim creates a common directory and puts toastr.service.ts in it. Then we see the code that goes into it. It’s a simple class that wraps each of the main toastr methods: success, info, warning and error.

The next module in the course is Routing and Navigating Pages.

--

--

Kevin O'Shaughnessy

Sr. Full Stack Web Dev promoting better professional practices, tools, solutions & helping others.