[Angular] Control the dependency lookup with @Host, @Self, @SkipSelf and @Optional
Very differently to AngularJS (v1.x), Angular now has a hierarchical dependency injector. That allows to specify service definitions as well as the service lifetime at various levels in our application. Whenever a service is requested, Angular will walk up the component tree and search for a matching definition. While in most cases that's perfectly fine, often you may want to take control over the dependency lookup. In this lesson we will learn how, by applying"@Host, @Self(), @SkipSelf() and @Optional().
@Optional:
When using @Optional, it set logger to null if the LoggerService is not provided instead of error out.
export class PersonComponent implements OnInit {
constructor(
@Optional()
public logger: LoggerService
) {}
ngOnInit() {}
doLog() {
if (this.logger) {
this.logger.log('Message from PersonComponent');
} else {
console.log('sorry, no logger available');
}
}
}
@SkipSelf:
If child component and parent component both using the same provider and we want to skip using child component's provider instead using parent's provider.
// Child
@Component({
selector: 'app-person',
template: `
<div style="border:1px;">
<p *ngIf="logger === null">I don't have a logger</p>
<button (click)="doLog()">write log</button>
</div>
`
providers: [
{
provide: LoggerService,
useFactory: loggerFactory('PersonComponent')
}
]
})
export class PersonComponent implements OnInit {
constructor(
@SkipSelf()
@Optional()
public logger: LoggerService
) {} ngOnInit() {} doLog() {
if (this.logger) {
this.logger.log('Message from PersonComponent');
} else {
console.log('sorry, no logger available');
}
}
}
// parent
@Component({
selector: 'app-root',
template: `
<h1>Angular Services</h1>
<app-person></app-person>
`,
providers: [
{
provide: LoggerService,
useFactory: loggerFactory('AppComponent')
}
]
})
export class AppComponent {}
SO in the end 'AppComponent ...' log message will appear in the console.
@Self():
Only using the provider for its own component.
@Component({
selector: 'app-person',
template: `
<div style="border:1px;">
<p *ngIf="logger === null">I don't have a logger</p>
<button (click)="doLog()">write log</button>
</div>
`
// providers: [
// {
// provide: LoggerService,
// useFactory: loggerFactory('PersonComponent')
// }
// ]
})
export class PersonComponent implements OnInit {
constructor(
@Self()
@Optional()
public logger: LoggerService
) {}
ngOnInit() {}
doLog() {
if (this.logger) {
this.logger.log('Message from PersonComponent');
} else {
console.log('sorry, no logger available');
}
}
}
So if PersonComponent has provider defined, it will use its own provider and will not continue searching parent component.
Often @Self can use togerther with @Optional, so if the provider is not defined, then set it to null.
@Host:
When we have directive, we might need to use @Host.
@Component({
selector: 'my-comp',
...
providers: [
MyService // Must have, other directive cannot find it, throw error.
]
})
<my-comp highlighted />
@Directive({
selector: 'highlighted'
})
export class Hightlighted {
// Use the provide inject directly into the host component
constructor (@Host private myService: MyService) {}
}
Because we cannot ensure that host element must have the Injection, if not, Angular will throw error, to prevent that, @Host normally work with @Optional together.
@Directive({
selector: 'highlighted'
})
export class Hightlighted {
// Use the provide inject directly into the host component
constructor (@Optional @Host private myService: MyService) {}
}
[Angular] Control the dependency lookup with @Host, @Self, @SkipSelf and @Optional的更多相关文章
- [Angular] Component's dependency injection
An Angular service registered on the NgModule is globally visible on the entire application. Moreove ...
- [Angular Tutorial] 7-XHRs & Dependency Injection
我们受够了在应用中用硬编码的方法嵌入三部电话!现在让我们用Angular内建的叫做$http的服务来从我们的服务器获取更大的数据集吧.我们将会使用Angular的依赖注入来为PhoneListCtrl ...
- [AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor
The upload class will be used in the service layer. Notice it has a constructor for file attribute, ...
- How to achieve dialog with lookup control
How to create a dialog with the lookup as a control, the other control SalesId ItemId lookup is the ...
- angular(常识)
我觉得angularjs是前端框架,而jquery只是前端工具,这两个还是没有可比性的. 看知乎上关于jquery和angular的对比http://www.zhihu.com/question/27 ...
- Angular 4+ 修仙之路
Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...
- Dependency Injection
Inversion of Control - Dependency Injection - Dependency Lookup loose coupling/maintainability/ late ...
- Hosting custom WPF calendar control in AX 2012
原作者: https://community.dynamics.com/ax/b/axilicious/archive/2013/05/20/hosting-custom-wpf-calendar-c ...
- Spring (一) IOC ( Inversion Of Control )
前序 现在小米手机很火就还拿小米手机来举例子,上一篇写的关于SSH框架搭建是从小米手机公司内个整个流程方面来考虑,如何提高效率生产效率,这篇博客主要从公司外部环境说明如何提高生产效率,那么怎么才能提高 ...
随机推荐
- td中嵌套table,让table完全填充父元素td
<table width="100% " cellspacing=0 cellpadding=0 border=1 > <tr> <td style= ...
- 新手学习selenium路线图(老司机亲手绘制)-学前篇【转载】
前言: 本来这篇是只在微信公众号(yoyoketang)上发布的,最近一搜,发现本很多人copy(copy公众号的,图片是加载不出来的)了,还没注明出处,不想多说什么,博客上也同步更新这篇吧! 最近群 ...
- cobbler部署安装
挂载光驱 # mount /dev/cdrom /mnt/ 安装cobbler所需软件 # yum install cobbler cobbler-web dhcp tftp-server pykic ...
- atom 插件
来源 个人博客 http://taoquns.com/paper/59ba5627a157197cdcc0a012 输入类 autocomplete-plus emmet go-to-line ato ...
- Codeforces 1023 D.Array Restoration-RMQ(ST)区间查询最值 (Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Fi)
D. Array Restoration 这题想一下就会发现是只要两个相同的数之间没有比它小的就可以,就是保存一下数第一次出现和最后一次出现的位置,然后查询一下这个区间就可以,如果有0的话就进行填充. ...
- (14)python 文件和流
打开文件 f=open('C:\Temp.txt') 读取数据 f.read(); 关闭文件 f.close();#关闭后将无法再读取 打开文件的方式 不写模式,默认是只读模式 1.r 打开只读文件, ...
- 数位dp模版(dp)
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> ...
- bzoj3942
有一个S串和一个T串,长度均小于1,000,000,设当前串为U串,然后从前往后枚举S串一个字符一个字符往U串里添加,若U串后缀为T,则去掉这个后缀继续流程.将s中的每一个字符压入栈暴力将s中的字符和 ...
- Codeforces 855E - Salazar Slytherin's Locket
855E - Salazar Slytherin's Locket 题意 给出一个区间,问这个区间内有多少个数满足,将这个数转化为某个进制后,所有数的数量都为偶数. 分析 谁能想到 数位DP 的裸题竟 ...
- 【bzoj2763】[JLOI2011]飞行路线 (分层图最短路)(优先队列dij)
[bzoj2763][JLOI2011]飞行路线 2014年3月25日1,7260 Description Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司.该航空公司一共在n个城 ...