Doing Inversion of Control (IoC) in Angular

Viewed 4956

Consider we have an interface called MapService, and two implementations: GoogleMapsService and LeafletMapService. I want a package (or Angular2?) to call the needed implementation rather than developers.

export interface MapService {
//define my API
}

@Injectable()
export class GoogleMapsService implements MapService {
//implement the API
}

That means, in the component I want the type of the service to be the interface (so not depending on the implementation):

import { Component } from '@angular/core';
import { MapService } from './map.service';
import { GoogleMapsService } from './google-maps.service'; 

@Component({
    template : `...`,
    providers: [GoogleMapsService]
})

export class MyComponent  {

  constructor(private googleMapsService : MapService) { //notice the type of the service here
  }
}

How can I achieve that?

3 Answers

Another solution would be to use an abstract class instead of an interface.

  export abstract class MapService{
   // ...
  }

make your service implements this abstract class and provide it

import { Component } from '@angular/core';
import { MapService } from './map.service';
import { GoogleMapsService } from './google-maps.service'; 

@Component({
    template : `...`,
    providers: [
      { provide: MapService, useClass: GoogleMapsService }
    ]
})

export class MyComponent  {

  constructor(private googleMapsService : MapService) {
  }
}
Related