Replacing Services with TypeScript Classes

Early Angular 1 applications predate the widespread use of module loaders.The strategy of this era was to concatenate source files and rely on Angular 1'sdependency injection as a poor-man's module loader. Often services were used tohouse libraries instead of stateful services.

During conversion, we will introduce Webpack as a module loader. For servicesthat lack state and don't heavily rely on other dependency injected services,we recommend rewriting them using TypeScript modules. The advantages of writingcode this way are:

  • It becomes framework agnostic (doesn't rely on Angular 1 explicitly)
  • It is easier to test
  • It instantly works with both Angular 1 and Angular 2
    Even services that depend on a limited set of Angular 1 services (e.g. $http)can be rewritten by depending on other libraries (e.g. window.fetch).

How do we get there?

  • Convert services using .factory to .service
    • Angular 2's @Injectable expects an object it can use new with,similar to how .service works (e.g. new CalculatorService())
  • Replace constructor functions with TypeScript class
  • Use the class directly by exporting it.

    Example

.factory original

  1. angular.module('calcapp', [])
  2. .factory('CalculatorService', function () {
  3. return {
  4. square: function (a) {
  5. return a*a;
  6. },
  7. cube: function (a) {
  8. return a*a*a;
  9. }
  10. };
  11. });

Conversion to .service

  1. angular.module('calcapp', [])
  2. .service('CalculatorService', function () {
  3. this.square = function (a) {
  4. return a*a;
  5. };
  6. this.cube = function (a) {
  7. return a*a*a;
  8. }
  9. });

Conversion to TypeScript class

  1. class CalculatorService {
  2. square (a) {
  3. return a*a;
  4. }
  5. cube (a) {
  6. return a*a*a;
  7. }
  8. }
  9. angular.module('calcapp', [])
  10. .service('CalculatorService', CalculatorService);

Skip the middleman

  1. export class CalculatorService { ... }
  2. // elsewhere
  3. import {CalculatorService} from './calculator.service';

原文: https://angular-2-training-book.rangle.io/handout/migrate/ng-upgrade/replacing_services.html