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.

  • 相关阅读:
    MongoDB存储
    python 查看文件名和文件路径
    Python遍历文件个文件夹
    Python图片缩放
    python opencv
    Python3 关于UnicodeDecodeError/UnicodeEncodeError: ‘gbk’ codec can’t decode/encode bytes类似的文本编码问题
    jmter使用
    HttpRunnerManager使用
    PostMan使用
    工作中的思想
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6839071.html
Copyright © 2011-2022 走看看