// 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.

最新文章

  1. Centos7无法上网
  2. JS---如何避免用户在请求时“猛击”
  3. python和numpy的版本、安装位置
  4. Maven构建简单的多模块项目
  5. Mybaits学习总结2
  6. DOM系列---进阶篇
  7. ***mysql中经度纬度字段用什么存储(关于mysql的float和decimal区别)
  8. 第三百二十八天 how can I 坚持
  9. shell&#39;s glob
  10. Java IO5:序列化与反序列化
  11. Qt 格式化字符串
  12. FileMode枚举
  13. Bootstrap里的文件分别表示什么?都有什么用?
  14. 智能优化算法对TSP问题的求解研究
  15. 【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II
  16. EF Core Model更新迁移
  17. [物理学与PDEs]第1章习题13 静磁场的矢势在媒质交界面上的条件
  18. React前端框架路由跳转,前端回车事件、禁止空格、提交方式等方法
  19. ThinkPHP 3.2 DEMO案例系列【phpmailer批量发送邮件】
  20. react router @4 和 vue路由 详解(三)react如何在路由里面定义一个子路由

热门文章

  1. Finance and Good Society
  2. [React] Define defaultProps and PropTypes as static methods in class component
  3. 【直接拿来用のandroid公共代码模块解析与分享】の Notification和NotificationManager
  4. POJ 1101 The Game(BFS+判方向)
  5. 用for和while循环求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!]
  6. samba-设定文件共享
  7. inflater-布局转化实现
  8. javascript创建对象的方法--原型模式
  9. InstallShield详细制作说明(四)
  10. 浅谈Git与SVN的使用感受