[Angular] Providers and useFactory

// service.ts

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class FoodService {
  constructor(
    private http: Http,
    private api: string
  ) {
    console.log(this.api);
  }
  getFood(): Observable<any[]> {
    return this.http.get(this.api)
      .map(response => response.json());
  }
}

 

Using factory provider:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

import { Observable } from 'rxjs/Observable';

import { FoodService } from '../food.service';

interface Drink {
  name: string,
  price: number
}

export function DrinkFactory(http) {
  return new FoodService(http, '/api/drinks');
}

@Component({
  selector: 'drink-viewer',
  providers: [
    {
      provide: FoodService,
      useFactory: DrinkFactory,
      deps: [
        Http
      ]
    }
  ],
  template: `
    <div>
      <div *ngFor="let item of items$ | async">
        {{ item.name }} {{ item.price | currency:'USD':true }}
      </div>
    </div>
  `
})
export class DrinkViewerComponent implements OnInit {
  items$: Observable<Drink[]>;
  constructor(private foodService: FoodService) {}
  ngOnInit() {
    this.items$ = this.foodService.getFood();
  }
}

Here we create 'DrinkFactory' as a named funciton, this is good for AOT, so recommended doing this way.

posted @ 2017-05-11 04:04  Zhentiw  阅读(1225)  评论(0编辑  收藏  举报