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. Mybatis拦截器介绍

    拦截器的一个作用就是我们可以拦截某些方法的调用,我们可以选择在这些被拦截的方法执行前后加上某些逻辑,也可以在执行这些被拦截的方法时执行自己的逻辑而不再执行被拦截的方法.Mybatis拦截器设计的一个初 ...

  2. webdriver(python) 学习笔记三

    知识点:简单的对象定位 对象的定位应该是自动化测试的核心,要想操作一个对象,首先应该识别这个对象.一个对象就是一个人一样,他会有各种的特征(属性),如比我们可以通过一个人的身份证号,姓名,或者他住在哪 ...

  3. IOS UIScrollView中 使用 touch 无法响应的问题

    添加一个 Category  然后在使用到 UIScrollView 的文件里面 导入这个头文件 就可以 // //  UIScrollView+UITouch.m //  alarm // //  ...

  4. 细雨学习笔记:Jmeter参数化

    目前我用到两种方式: 1)某个参数,值不常改变的,好多地方都用到:请用“用户定义的变量” 用户组,右键--添加--配置原件--用户定义的变量,在这添加. 如何使用呢?在需要用到此参数的地方这样引用: ...

  5. OpenGL超级宝典第5版&&开发环境搭建

    参考:http://www.zyh1690.org/build-opengl-super-bible-fifth-edition-development-environment/ 环境搭建的测试环境为 ...

  6. 试验Windows Embedded Standard 7 Service Pack 1 Evaluation Edition

    =========================================== 是否支持再使用 RT 7 Lite 精简 ? ================================= ...

  7. 【和我一起学python吧】python的数据类型

    python的元组.列表.字典数据类型是很python(there python is a adjective )的数据结构.这些结构都是经过足够优化后的,所以如果使用好的话,在某些area会有很大的 ...

  8. Canvas入门(3):图像处理和绘制文字

    来源:http://www.ido321.com/997.html 一.图像处理(非特别说明,所有结果均来自最新版Google) 在HTML 5中,不仅可以使用Canvas API绘制图形,也可以用于 ...

  9. dwr消息推送

    闲来无事,把自己关于对dwr消息推送的实现过程描述一番. 首先第一步,当然在工程中是加入dwr.jar了,接着在web.xml中配置以下代码 <servlet> <servlet-n ...

  10. Android自定义TTF字体

    前言: 在Android Design中一个设计手册.在设计手册中有常用的UI图标,图标大小规范等. 其中,有一个TTF字体,以前感觉没什么用.但是我在学习时,常看到有许多开发者使用Google 提供 ...