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