klabautermann123
5/28/2017 - 12:18 PM

angular 2 dependency injection: Swith MockService https://github.com/Farata/angular2typescript/tree/master/Angular4/di-samples/src/app/swit

import {Product} from "./product"

export class ProductService {
  getProduct(): Product {
    // Code making an HTTP request to get actual product details could go here
    return new Product('iPhone 7');
  }
}
import {ProductService} from "./product.service";
import {Product} from "./product";

export class MockProductService implements ProductService {
  getProduct(): Product {
    return new Product('Samsung 7');
  }
}
import {Component} from '@angular/core';
import {MockProductService} from "./mock.product.service";
import {Product} from "./product";
import {ProductService} from "./product.service";



//++++++++++++++++++++++++++++++++++++++++++
// Example using a custom Service Factory
//++++++++++++++++++++++++++++++++++++++++++



//-----------------------------
// Service Factory Definition
//------------------------------

export function productServiceFactory (isDev:boolean) {
  if (isDev){
    return new MockProductService();
  }
  else{
    return new ProductService();
  }

};




@Component({

  selector: 'product2',
  providers:[
    {
      provide: ProductService,
      useFactory: productServiceFactory, 
      deps: ["IS_DEV_ENVIRONMENT"]
    }
    ],
  template: '{{product.title}}'
})

export class Product2Component {
  product: Product;
  constructor(productService: ProductService) {
    this.product = productService.getProduct();
  }
}











/*@Component({
  selector: 'product2',

  providers:[{
    provide: ProductService,
    useFactory: (isDev) => {
      if (isDev){
        return new MockProductService();
      } else{
        return new ProductService();
      }
    }, deps: ["IS_DEV_ENVIRONMENT"]}],

  template: '{{product.title}}'
})
export class Product2Component {
  product: Product;

  constructor(productService: ProductService) {
    this.product = productService.getProduct();
  }
}*/
import {Component} from '@angular/core';
import {MockProductService} from "./mock.product.service";
import {Product} from "./product";
import {ProductService} from "./product.service";

@Component({
  selector: 'product2',
  template: '{{product.title}}',
  providers: [{provide:ProductService, useClass:MockProductService}]
})
export class Product2Component {
  product: Product;

  constructor(private productService: ProductService) {
    this.product = productService.getProduct();
  }
}