Dependecies aren’t always objects created by classes or factory functions. Sometimes, all we really want is inject a simple value, which can be a primitive, or maybe just a configuration object. For these cases, we can use value providers and in this lesson we’ll discuss, how they are created.

For example we have this code:

import {LoggerProvider} from './LoggerProvider';
import (Http) from '@angular/http';
import {Injectable} from '@angular/core'; @Injectable
export class TodoService{ apiUrl : string = "http://localhost:3000/api" constructor(private logger: LoggerProvider, private http: Http){ } getTodos(){
this.logger.debug('Items', this.todos);
return this.http.get(`${this.apiUrl}/todos`).map(res => res.json());
}
}

Code use hard coded 'apiUrl' to get data from backend. It would be better to inject apiUrl instead of hard coded.

app.ts:

 providers: [
TodoService,
ConsoleService,
TranslateService,
,{
provide: LoggerProvider, useFactory: (cs, ts) => {
return new LoggerProvider(cs, ts, true)
},
deps: [ConsoleService, TranslateService]
}
,{
provide: apiUrl,
useValue: 'http://localhost:3000/api'
}
],

Inside providers we add another value provider. Using keyword 'useValue'.

Then in the TodoService, we can do:

import {LoggerProvider} from './LoggerProvider';
import {Injectable} from '@angular/core';
import {Http} from '@angular/core';
import {Inject} from '@angular/core'; @Injectable
export class TodoService{ constructor(@Inject(apiUrl) private apiUrl, private logger: LoggerProvider, private http: Http){ } getTodos(){
this.logger.debug('Items', this.todos);
return this.http.get(`${this.apiUrl}/todos`).map(res => res.json());
}
}

We add @Inject because 'apiUrl' doesn't have annotation for 'apiUrl'.  Angular provide @Inject for this case. @inject is a decorator that we can attach to the constructor parameter so we can annotate them with the required metadata.

Another thing to note is that @inject takes any token, not just strings.

We can also do:

constructor(@Inject(apiUrl) private apiUrl, @Inject(LoggerProvider) private logger, private http: Http){ }

This is useful if we happen to write our Angular 2 application in a language other than TypeScript, where type annotations don't exist.

[Angular 2] Value Providers & @Inject的更多相关文章

  1. [Angular] Pipes as providers

    In this example, we are going to see how to use Pipe as providers inject into component. We have the ...

  2. [Angular 2] BYPASSING PROVIDERS IN ANGULAR 2

    Artical --> BYPASSING PROVIDERS IN ANGULAR 2 Here trying to solve one problem: On the left hand s ...

  3. [Angular] Difference between Providers and ViewProviders

    For example we have a component: class TodoList { private todos: Todo[] = []; add(todo: Todo) {} rem ...

  4. angular使用@angular/material 出现"export 'ɵɵinject' was not found in '@angular/core'

    WARNING in ./node_modules/@angular/cdk/esm5/a11y.es5.js 2324:206-214 "export 'ɵɵinject' was not ...

  5. [Angular 2] Using the @Inject decorator

    TypeScript is used heavily as we build up our application, but TypeScript isn’t required. If you wan ...

  6. Angular源代码学习笔记-原创

    时间:2014年12月15日 14:15:10 /** * @license AngularJS v1.3.0-beta.15 * (c) 2010-2014 Google, Inc. http:// ...

  7. Angular SSR 探究

    一般来说,普通的 Angular 应用是在 浏览器 中运行,在 DOM 中对页面进行渲染,并与用户进行交互.而 Angular Universal 是在 服务端 进行渲染(Server-Side Re ...

  8. Angular CurrencyPipe货币管道关于人民币符号¥的问题

    做项目(Angular项目)时经常需要处理金额的显示,需要在金额前面加上¥,但又不想用简单在前面加"¥"这么不优雅的方式,于是想到了CurrencyPipe.毕竟,Currency ...

  9. @angular/cli项目构建--interceptor

    JWTInterceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterce ...

随机推荐

  1. codeforces 681D Gifts by the List dfs+构造

    题意:给你一个森林,表示其祖先关系(自己也是自己的祖先),每个人有一个礼物(要送给这个人的固定的一个祖先) 让你构造一个序列,使得的对于每个人,这个序列中第一个出现的他的祖先,是他要送礼物的的那个祖先 ...

  2. CSS书写规范、顺序

    写了这么久的CSS,但大部分前端er都没有按照良好的CSS书写规范来写CSS代码,这样会影响代码的阅读体验,总结一个CSS书写规范.CSS书写顺序供大家参考,这些是参考了国外一些文章以及我的个人经验总 ...

  3. SQL合并时间段的问题

    假设表结构如下所示: Tsheets 字段名 字段类型 约束 id CHAR(10) PRIMARY KEY start_date DATE CHECK(start_date<= end_dat ...

  4. CSS基础知识—【结构、层叠、视觉格式化】

    结构和层叠 选择器的优先级顺序: style[内联元素]选择器>Id选择器>类选择器 属性选择器>元素选择器>通配器选择器 重要性:@important 有这个标记的属性值,优 ...

  5. bzoj 1109 [POI2007]堆积木Klo(LIS)

    [题意] n个数的序列,删除一个数后序列左移,求最后满足i==a[i]的最大个数. [思路] 设最终得到a[i]==i的序列为s,则s应满足: i<j,a[i]<a[j],i-a[i]&l ...

  6. (四面体)CCPC网络赛 HDU5839 Special Tetrahedron

    CCPC网络赛 HDU5839 Special Tetrahedron 题意:n个点,选四个出来组成四面体,要符合四面体至少四条边相等,若四条边相等则剩下两条边不相邻,求个数 思路:枚举四面体上一条线 ...

  7. 多校5 1004 HDU5784 统计锐角三角形数目

    http://acm.hdu.edu.cn/showproblem.php?pid=5784 题意:n个点,找多少个锐角三角形数目 思路:极角排序+two pointers 当前选择的点集要倍增一倍, ...

  8. DRAM 内存介绍(一)

    转载自博客大神迈克老狼的blog: http://www.cnblogs.com/mikewolf2002/archive/2012/11/13/2768804.html 参考资料:http://ww ...

  9. Dapper基础用法

    假如你喜欢原生的Sql语句,又喜欢ORM的简单,那你一定会喜欢上Dapper这款ROM.点击下载Dapper的优势:1,Dapper是一个轻型的ORM类.代码就一个SqlMapper.cs文件,编译后 ...

  10. Android问题-新电脑新系统WIN764位上安装简版本的XE8提示“Unit not found: 'System'”

    问题现象:电脑太慢,重安新系统,所以要安DELPHIXE8,但安装过程中出现二次杀软件提示,我都选的是通过.但是XE8过程到最后的"Create AVD"时出现一个错误(具体是什么 ...