Services 3.1

Send feedback

As the Tour of Heroes app evolves, you’ll add more components that need access to hero data.

Instead of copying and pasting the same code over and over, you’ll create a single reusable data service and inject it into the components that need it. Using a separate service keeps components lean and focused on supporting the view, and makes it easy to unit-test components with a mock service.

Because data services are invariably asynchronous, you’ll finish the page with a Future-based version of the data service.

When you’re done with this page, the app should look like this .

Where you left off

Before continuing with the Tour of Heroes, verify that you have the following structure. If not, go back to the previous pages.

  • angular_tour_of_heroes
    • lib
      • app_component.dart
      • src
        • hero.dart
        • hero_detail_component.dart
    • web
      • index.html
      • main.dart
      • styles.css
    • pubspec.yaml

If the app isn’t running already, launch the app. As you make changes, keep it running by reloading the browser window.

Creating a hero service

The stakeholders want to show the heroes in various ways on different pages. Users can already select a hero from a list. Soon you’ll add a dashboard with the top performing heroes and create a separate view for editing hero details. All three views need hero data.

At the moment, the AppComponent defines mock heroes for display. However, defining heroes is not the component’s job, and you can’t easily share the list of heroes with other components and views. In this page, you’ll move the hero data acquisition business to a single service that provides the data and share that service with all components that need the data.

Create HeroService

Create a file in the lib folder called hero_service.dart.

The naming convention for service files is the service name in lowercase followed by _service. For a multi-word service name, use lower snake_case. For example, the filename for SpecialSuperHeroService is special_super_hero_service.dart.

Name the class HeroService.

lib/src/hero_service.dart (starting point)

import 'package:angular2/angular2.dart'; import 'hero.dart'; import 'mock_heroes.dart'; @Injectable() class HeroService { }

Injectable services

Notice that you used an @Injectable() annotation.

Don’t forget the parentheses. Omitting them leads to an error that’s difficult to diagnose.

Getting hero data

Add a getHeroes() method stub.

lib/src/hero_service.dart (getHeroes stub)

@Injectable() class HeroService { List<Hero> getHeroes() {} }

The HeroService could get Hero data from anywhere—a web service, local storage, or a mock data source. Removing data access from the component means you can change your mind about the implementation anytime, without touching the components that need hero data.

Move the mock hero data

Cut the mockHeroes list from app_component.dart and paste it to a new file in the lib folder named mock_heroes.dart. Additionally, copy the import 'hero.dart' statement because the heroes list uses the Hero class.


import 'hero.dart'; final List<Hero> mockHeroes = [ new Hero(11, 'Mr. Nice'), new Hero(12, 'Narco'), new Hero(13, 'Bombasto'), new Hero(14, 'Celeritas'), new Hero(15, 'Magneta'), new Hero(16, 'RubberMan'), new Hero(17, 'Dynama'), new Hero(18, 'Dr IQ'), new Hero(19, 'Magma'), new Hero(20, 'Tornado') ];

In app_component.dart, where you cut away the mockHeroes list, add an uninitialized heroes property:

lib/app_component.dart (excerpt)

List<Hero> heroes;

Return mocked hero data

Back in the HeroService, import the mock mockHeroes and return it from the getHeroes() method. The HeroService looks like this:

lib/src/hero_service.dart (final)

import 'package:angular2/angular2.dart'; import 'hero.dart'; import 'mock_heroes.dart'; @Injectable() class HeroService { List<Hero> getHeroes() => mockHeroes; }

Use the hero service

You’re ready to use the HeroService in other components, starting with AppComponent.

Import the HeroService so that you can reference it in the code.

lib/app_component.dart (hero service import)

import 'src/hero_service.dart';

Don’t use new with the HeroService

How should the AppComponent acquire an instance of HeroService?

You could create a new instance of the HeroService with new like this:

lib/app_component.dart (excerpt)

HeroService heroService = new HeroService(); // don't do this

However, this option isn’t ideal for the following reasons:

  • The component has to know how to create a HeroService. If you change the HeroService constructor, you must find and update every place you created the service. Patching code in multiple places is error prone and adds to the test burden.
  • You create a service each time you use new. What if the service caches heroes and shares that cache with others? You couldn’t do that.
  • With the AppComponent locked into a specific implementation of the HeroService, switching implementations for different scenarios, such as operating offline or using different mocked versions for testing, would be difficult.

Inject HeroService

Instead of using the new expression, add these lines:

  • Add a private HeroService property.
  • Add a constructor that initializes the private property.
  • Add HeroService to the component’s providers metadata.

Here are the property and the constructor:

lib/app_component.dart (constructor)

final HeroService _heroService; AppComponent(this._heroService);

The constructor does nothing except set the _heroService property. The HeroService type of _heroService identifies the constructor’s parameter as a HeroService injection point.

Now Angular knows to supply a HeroService instance when it creates a new AppComponent.

Read more about dependency injection in the Dependency Injection page.

The injector doesn’t know yet how to create a HeroService. If you ran the code now, Angular would fail with this error:

EXCEPTION: No provider for HeroService! (AppComponent -> HeroService)

To teach the injector how to make a HeroService, add the following providers list as the last parameter of the @Component annotation.

lib/app_component.dart (providers)

providers: const [HeroService],

The providers parameter tells Angular to create a fresh instance of the HeroService when it creates an AppComponent. The AppComponent, as well as its child components, can use that service to get hero data.

The AppComponent.getHeroes() method

The service is in a heroService private variable.

You could call the service and get the data in one line.

heroes = _heroService.getHeroes();

You don’t really need a dedicated method to wrap one line. Write it anyway:

lib/app_component.dart (getHeroes)

void getHeroes() { heroes = _heroService.getHeroes(); }

The ngOnInit lifecycle hook

AppComponent should fetch and display hero data with no issues.

You might be tempted to call the getHeroes() method in a constructor, but a constructor should not contain complex logic, especially a constructor that calls a server, such as a data access method. A constructor is for simple initializations, like wiring constructor parameters to properties.

To have Angular call getHeroes(), you can implement the Angular ngOnInit lifecycle hook. Angular offers interfaces for tapping into critical moments in the component lifecycle: at creation, after each change, and at its eventual destruction.

Each interface has a single method. When the component implements that method, Angular calls it at the appropriate time.

Read more about lifecycle hooks in the Lifecycle Hooks page.

Add OnInit to the list of interfaces implemented by AppComponent:

lib/app_component.dart (ngOnInit stub)

import 'package:angular2/angular2.dart'; class AppComponent implements OnInit { void ngOnInit() { } }

Write an ngOnInit() method with the initialization logic inside. Angular will call it at the right time. In this case, initialize by calling getHeroes().

void ngOnInit() { getHeroes(); }

The app should run as expected, showing a list of heroes and a hero detail view when you click on a hero name.

Async hero services

The HeroService returns a list of mock heroes immediately; its getHeroes() signature is synchronous.

lib/app_component.dart (get-heroes)

heroes = _heroService.getHeroes();

Eventually, the hero data will come from a remote server. When using a remote server, users don’t have to wait for the server to respond; additionally, you aren’t able to block the UI during the wait.

To coordinate the view with the response, you can use Futures, which is an asynchronous technique that changes the signature of the getHeroes() method.

The hero service returns a Future

A Future represents a future computation or value. Using a Future, you can register callback functions that will be invoked when the computation completes (and results are ready), or when a computational error needs to be reported.

This is a simplified explanation. Read more about Futures in the Dart language tutorial on Asynchronous Programming: Futures.

Add an import of 'dart:async' because it defines Future, and update the HeroService with this Future-returning getHeroes() method:

lib/src/hero_service.dart (excerpt)

Future<List<Hero>> getHeroes() async => mockHeroes;

You’re still mocking the data. You’re simulating the behavior of an ultra-fast, zero-latency server, by returning a Future whose mock heroes become available immediately.

Marking a method as async automatically sets the return type to Future. For more information on async functions, see Declaring async functions in the Dart language tour.

Processing the Future

As a result of the change to HeroService, the app component’s heroes property is now a Future rather than a list of heroes. You have to change the implementation to process the Future result when it completes. When the Future completes successfully, you’ll have heroes to display.

Here is the current implementation:

lib/app_component.dart (synchronous getHeroes)

void getHeroes() { heroes = _heroService.getHeroes(); }

Pass the callback function as an argument to the Future.then() method:

lib/app_component.dart (asynchronous getHeroes)

void getHeroes() { _heroService.getHeroes().then((heroes) => this.heroes = heroes); }

The callback sets the component’s heroes property to the list of heroes returned by the service.

The app still runs, showing a list of heroes, and responding to a name selection with a detail view.

Use async/await

An asynchronous method containing one or more Future.then() methods can be difficult to read and understand. Thankfully, Dart’s async/await language feature lets you write asynchronous code that looks just like synchronous code. Rewrite getHeroes():

lib/app_component.dart (revised async/await getHeroes)

Future<Null> getHeroes() async { heroes = await _heroService.getHeroes(); }

The Future<Null> return type is the asynchronous equivalent of void.

Read more about asynchronous programming using async/await in the Async and await section of the Dart language tutorial on Asynchronous Programming: Futures.

At the end of this page, Appendix: Take it slow describes what the app might be like with a poor connection.

Review the app structure

Verify that you have the following structure after all of your refactoring:

  • angular_tour_of_heroes
    • lib
      • app_component.dart
      • src
        • hero.dart
        • hero_detail_component.dart
        • hero_service.dart
        • mock_heroes.dart
    • web
      • index.html
      • main.dart
      • styles.css
    • pubspec.yaml

Here are the code files discussed in this page.

import 'dart:async'; import 'package:angular2/angular2.dart'; import 'hero.dart'; import 'mock_heroes.dart'; @Injectable() class HeroService { Future<List<Hero>> getHeroes() async => mockHeroes; } import 'dart:async'; import 'package:angular2/angular2.dart'; import 'src/hero.dart'; import 'src/hero_detail_component.dart'; import 'src/hero_service.dart'; @Component( selector: 'my-app', template: ''' <h1>{{title}}</h1> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes" [class.selected]="hero == selectedHero" (click)="onSelect(hero)"> <span class="badge">{{}}</span> {{}} </li> </ul> <hero-detail [hero]="selectedHero"></hero-detail> ''', styles: const [ ''' .selected { background-color: #CFD8DC !important; color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0em; height: 1.6em; border-radius: 4px; } .heroes li.selected:hover { color: white; } .heroes li:hover { color: #607D8B; background-color: #EEE; left: .1em; } .heroes .text { position: relative; top: -3px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0em 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0px 0px 4px; } ''' ], directives: const [CORE_DIRECTIVES, HeroDetailComponent], providers: const [HeroService], ) class AppComponent implements OnInit { String title = 'Tour of Heroes'; List<Hero> heroes; Hero selectedHero; final HeroService _heroService; AppComponent(this._heroService); Future<Null> getHeroes() async { heroes = await _heroService.getHeroes(); } void ngOnInit() { getHeroes(); } void onSelect(Hero hero) { selectedHero = hero; } } import 'hero.dart'; final List<Hero> mockHeroes = [ new Hero(11, 'Mr. Nice'), new Hero(12, 'Narco'), new Hero(13, 'Bombasto'), new Hero(14, 'Celeritas'), new Hero(15, 'Magneta'), new Hero(16, 'RubberMan'), new Hero(17, 'Dynama'), new Hero(18, 'Dr IQ'), new Hero(19, 'Magma'), new Hero(20, 'Tornado') ];

The road you’ve travelled

Here’s what you achieved in this page:

  • You created a service class that can be shared by many components.
  • You used the ngOnInit lifecycle hook to get the hero data when the AppComponent activates.
  • You defined the HeroService as a provider for the AppComponent.
  • You created mock hero data and imported them into the service.
  • You designed the service to return a Future and the component to get the data from the Future.

Your app should look like this .

The road ahead

The Tour of Heroes has become more reusable using shared components and services. The next goal is to create a dashboard, add menu links that route between the views, and format data in a template. As the app evolves, you’ll discover how to design it to make it easier to grow and maintain.

Read about the Angular component router and navigation among the views in the next tutorial page.

Appendix: Take it slow

To simulate a slow connection, add the following getHeroesSlowly() method to the HeroService.

lib/src/hero_service.dart (getHeroesSlowly)

Future<List<Hero>> getHeroesSlowly() { return new Future.delayed(const Duration(seconds: 2), getHeroes); }

Like getHeroes(), it also returns a Future, but this Future waits two seconds before completing.

Back in the AppComponent, replace getHeroes() with getHeroesSlowly() and see how the app behaves.