zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    c# WinForm 文本输入对话框
    C# 打印 长字符串自动换行
    Jquery通过AJAX从后台获取数据显示在表格上(复选)
    jquery通过AJAX从后台获取信息并显示在表格上的类
    迟来的总结与规划
    Tools
    HTML+CSS 学习清单
    JQuery 入门学习列表
    Git(Mac OSX下)
    dom 元素占据高度
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6839071.html
Copyright © 2011-2022 走看看