[Angular 2] Value Providers & @Inject
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的更多相关文章
- [Angular] Pipes as providers
In this example, we are going to see how to use Pipe as providers inject into component. We have the ...
- [Angular 2] BYPASSING PROVIDERS IN ANGULAR 2
Artical --> BYPASSING PROVIDERS IN ANGULAR 2 Here trying to solve one problem: On the left hand s ...
- [Angular] Difference between Providers and ViewProviders
For example we have a component: class TodoList { private todos: Todo[] = []; add(todo: Todo) {} rem ...
- 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 ...
- [Angular 2] Using the @Inject decorator
TypeScript is used heavily as we build up our application, but TypeScript isn’t required. If you wan ...
- Angular源代码学习笔记-原创
时间:2014年12月15日 14:15:10 /** * @license AngularJS v1.3.0-beta.15 * (c) 2010-2014 Google, Inc. http:// ...
- Angular SSR 探究
一般来说,普通的 Angular 应用是在 浏览器 中运行,在 DOM 中对页面进行渲染,并与用户进行交互.而 Angular Universal 是在 服务端 进行渲染(Server-Side Re ...
- Angular CurrencyPipe货币管道关于人民币符号¥的问题
做项目(Angular项目)时经常需要处理金额的显示,需要在金额前面加上¥,但又不想用简单在前面加"¥"这么不优雅的方式,于是想到了CurrencyPipe.毕竟,Currency ...
- @angular/cli项目构建--interceptor
JWTInterceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterce ...
随机推荐
- 常见设计模式解析和实现(C++)FlyWeight模式
作用:运用共享技术有效地支持大量细粒度的对象 UML结构图: 解析: Flyweight模式在大量使用一些可以被共享的对象的时候使用.比如,在QQ聊天时很多时候你懒得回复又不得不回复,一般会用一些客套 ...
- 【和我一起学python吧】初学Python,版本如何选择?
早在四年多以前,在我进入英才网之前,去面试过一家海归创业的公司.他们需要的是有unix开发经验的技术人员,但是因为他们当时所处的阶段对很多成熟 技术人员不是很吸引,所以条件放宽为熟悉面向对象的程序开发 ...
- .net高级技术(class0515)
本次课程中讲的有的东西都是根据初学者的认知规律进行了调整,并不是严谨的,比如很多地方在多AppDomain条件下很多说法就不对了,但是说严谨了大家就晕了,因此继续不严谨的讲吧. 很多面试题都在这阶段的 ...
- 利用HTML 5中的Menu和Menuitem元素快速创建菜单
原文:Introducing the HTML5 “Menu” and “Menuitem” Elements 译文:HTML 5中Menu和Menuitem的元素介绍 译者:dwqs 今天向你介绍H ...
- SVM原理简介
本文只是简单介绍一下SVM的理论框架,想要详细了解当中细节问题处理可以参看后续章节或者网上各种详细资料.推荐Andrew Ng的斯坦福大学机器学习课程. 年代中期发展起来的基于统计学习理论的一种机器学 ...
- How to interact with the Chef Server using the Chef Server API using Shell script
!/usr/bin/env bash _chef_dir () { # Helper function: # Recursive function that searches for chef c ...
- AIM Tech Round 3
题目链接:(做出几道说几道^_^) A.Juicer B.Checkpoints C.Letters Cyclic Shift 思路: A题每次加上橘子的体积,超过就清零,计数器加1 B题比较 (lo ...
- linux下开发c++第二弹--helloworld与makefile
一:hello world sudo vim hello.cpp 输入 g++ -o hello hello.cpp 获得hello 输入 ./hello 运行,显示结果hello world! ...
- CSS 去掉IE10中type=password中的眼睛图标
在IE10中,input[type=password],如果我们输入内容后,内容会变成圆点,这与以前一样,但后面多了一个眼睛图标,我们鼠标移过去按下会出现输入内容.有时我们想去掉这功能.IE10允许我 ...
- No module named BeautifulSoup
遇到 No module named BeautifulSoup 错误,但是的确从官方下载了BeautifulSoup,并安装成功. 后来才发现,有两个BeautifulSoup的版本,一个是2012 ...