[Angular] Providers and useFactory
2024-08-31 21:15:50
// 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.
最新文章
- Centos7无法上网
- JS---如何避免用户在请求时“猛击”
- python和numpy的版本、安装位置
- Maven构建简单的多模块项目
- Mybaits学习总结2
- DOM系列---进阶篇
- ***mysql中经度纬度字段用什么存储(关于mysql的float和decimal区别)
- 第三百二十八天 how can I 坚持
- shell&#39;s glob
- Java IO5:序列化与反序列化
- Qt 格式化字符串
- FileMode枚举
- Bootstrap里的文件分别表示什么?都有什么用?
- 智能优化算法对TSP问题的求解研究
- 【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II
- EF Core Model更新迁移
- [物理学与PDEs]第1章习题13 静磁场的矢势在媒质交界面上的条件
- React前端框架路由跳转,前端回车事件、禁止空格、提交方式等方法
- ThinkPHP 3.2 DEMO案例系列【phpmailer批量发送邮件】
- react router @4 和 vue路由 详解(三)react如何在路由里面定义一个子路由
热门文章
- Finance and Good Society
- [React] Define defaultProps and PropTypes as static methods in class component
- 【直接拿来用のandroid公共代码模块解析与分享】の Notification和NotificationManager
- POJ 1101 The Game(BFS+判方向)
- 用for和while循环求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!]
- samba-设定文件共享
- inflater-布局转化实现
- javascript创建对象的方法--原型模式
- InstallShield详细制作说明(四)
- 浅谈Git与SVN的使用感受