Angular 2 Services

Creating a Service


To create a new service in Angular 2 we need to first import Injectable:

import { Injectable } from '@angular/core';

Then we need to invoke the @Injectable decorator on the class we want to use as an Angular service. This essentially tells Angular that this class can be injected via dependency injection.


export class UserService {
  constructor () {}

  currentUser = 'Eric';

  setUser(name) {
    this.currentUser = name;

In Angular 1 we used strings to manage the identity of services for DI, but in Angular 2 we actually use the signature of the class itself (which is why we have to import the service into a component's file in order to inject it):


import { Component, EventEmitter, Input, Output } from '@angular/core';
+import { UserService } from '../user.service'

  selector: 'layout-header',
  templateUrl: 'src/app/shared/layout/header.component.html'
export class HeaderComponent {
+    private userService: UserService
  ) {}

+  user = this.userService.currentUser;

  changeUser(newUser) {
+    this.userService.setUser(newUser);

In the HeaderComponent's code above, it injects the UserService that's available as a private variable on the classed named userService. private means that the variable can only be accessed within this class, and it's Angular convention to do a lowercased version of your service name when injecting it (i.e. UserService should become userService).

You can view the working code here:

Now when you click the button it should change the name in the component... but it doesn't, and no errors are being thrown. What gives?

Well it turns out that Angular 1 would perform data binding like this with the $digest cycle. With Angular 2 we no longer have $digest — so what do we do? This is where RxJS and Observables come in, as they solve this problem in an incredibly powerful yet elegant way.

In the next tutorial we're going to dig into rxjs and observables and then modify the user service to work properly.