Unlike 'useClass', 'useExisting' doesn't create a new instance when you register your service inside ngmodule.

'useExisting' also can limit the function call, for example:

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
) {
}
getSides(): Observable<any[]> {
return this.http.get('/api/sides')
.map(response => response.json());
}
getPizzas(): Observable<any[]> {
return this.http.get('/api/pizzas')
.map(response => response.json());
}
getDrinks(): Observable<any[]> {
return this.http.get('/api/drinks')
.map(response => response.json());
}
}

We have a service which has three methods 'getSides', 'getPizzas' & 'getDrinks'.

Inside one of component, we use 'useExisting' to create an abstract class 'DrinkService', which return include one methods which 'DrinkService' needs -- getDrinks()

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 abstract class DrinkService {
getDrinks: () => Observable<Drink[]>;
} @Component({
selector: 'drink-viewer',
providers: [
{ provide: DrinkService, useExisting: FoodService }
],
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: DrinkService) {}
ngOnInit() {
this.items$ = this.foodService.getDrinks();
}
}

This can help TypeScript to limit the methods available to our Drink component, because in drink component, we don't need 'getPizzas' or 'getSides'. But this is just compile checking, it will still call the methods 'getPizzas' or 'getSides' during run time.

最新文章

  1. Dijkstra 算法
  2. PCB的封装尺寸
  3. 7、SQL Server索引、表压缩
  4. Spring+Mybatis 手动控制事务
  5. python学习笔记二 数据类型(基础篇)
  6. 用Eclipse+ADT创建可运行项目,创建lib项目,引用一个lib项目
  7. USB Video Class及其实现
  8. python语言磁力搜索引擎源码公开,基于DHT协议
  9. JTextArea Demo
  10. 极化SAR图像基础知识(2)
  11. nmap扫描某段网络连通性
  12. python小技巧01递归解释内嵌
  13. OO第二单元总结
  14. ThinkPad T400 键帽下面的X支架的安装方法
  15. 在泛微系统中修改AD密码的配置
  16. PAMIE模块安装
  17. hadoop 常见 命令
  18. android--实现通过点击链接打开apk(应用图标在桌面消失)
  19. Gym 101201J Shopping (线段树+取模)
  20. Mysql 创建表和删除表

热门文章

  1. PA模块经常使用表
  2. 深入理解javascript之原型
  3. mk-编译信息的意义
  4. javascript创建对象的方法--动态原型模式
  5. 使用Multiplayer Networking做一个简单的多人游戏例子-1/2(换一种方法)
  6. 洛谷 P1100 高低位交换
  7. Ubuntu配置sublime text 3的c编译环境
  8. POJ Oulipo(KMP模板题)
  9. 10.Maven依赖排除 禁止依赖传递 取消依赖的方法
  10. M1卡操作