Monday, November 28, 2016

Angular 2 Part 5.2 - Service using Dependency Injector

In Part 5.1, we introduced the simplest way to create service. However, this is yet a best solution because we need to create new RacingDataService every time when we need to fetch the data. This would used up more memory.

This is where dependency injection come in. When you run Angular 2 application, it creates a dependency injector. An injector is in charge of knowing how to create and send things.

One of the advantages is that dependency injection know how to resend the same service if the injector already created a service.

There are 3 steps to make all work in our example:

1. Add the injectable decorator to racing-data.service.ts.
...
import { Injectable } from '@angular/core';

@injectable()
...

2. Let our injector know about our service by naming it as a provider in main.ts
@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

3. Inject the dependency into our car-parts.component.ts
export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
  }

  ...
}

Now our application is more scalable because our dependencies aren't strongly tied our classes.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

No comments:

Post a Comment