[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框架搭建是从小米手机公司内个整个流程方面来考虑,如何提高效率生产效率,这篇博客主要从公司外部环境说明如何提高生产效率,那么怎么才能提高 ...
随机推荐
- 【 总结 】linux中test命令详解
test命令在bash shell脚本中经常以中括号([])的形式出现,而且在脚本中使用字母来表示比符号表示更专业,出错率更低. 测试标志 代表意义 文件名.文件类型 -e 该文件名是否存在 -f 该 ...
- Liquibase 快速开始
Step 1 :创建Changelog文件,所有的数据库变动都会保存在Changelog文件中 <?xml version="1.0" encoding="UTF- ...
- Jquery实现全选和取消全选的方法
<input type="checkbox" id="all" />全选<br /> <input type="chec ...
- java 8中撤销永久代,引入元空间
撤销永久代,引入元空间: 在 JDK 1.8 中,HotSpot 已经没有 “PermGen space”这个空间了,取而代之是一个叫做 Metaspace(元空间) 的东西. Java7中已经将字符 ...
- 【转】Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址
Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址 关注finddreams,一起分享,一起进步: http://blog.csdn.net/finddr ...
- hdu5819
补多校系列,具体见多校题解http://www.cnblogs.com/duoxiao/p/5777700.html 值得注意的是如果当前i初始向左,前i个骑士最终只有1个向右 对于f[i][1]状态 ...
- “equals”和“==”
“equals”和“==” 首先对于基本类型来说,当值相同的时候,地址也是相同的,所以可以使用“==”进行比较,但是对于equals来说,equals比较的是栈中引用指向的堆中的对象.所以在比较对象的 ...
- Dart类
Dart中没有访问控制符,无论类还是方法默认都是public 1.构造函数 构造函数可以没有方法体,并且this可以直接在传参时直接对实例赋值 Bicycle(this.cadence, this.s ...
- 福州三中集训day1
第一天感觉很是不友好,好在我是学过搜索之后才听的课,不然估计得死在教室…. 某zld犇犇讲的很是强?今天主要是讲枚举和DFS,几道经典题目讲完,还没到下课时间, 然后讲起了float. 有空整理一下吧 ...
- Codeforces #430 Div2 C
#430 Div2 C 题意 给出一棵带点权的树,每一个节点的答案为从当前节点到根节点路径上所有节点权值的最大公因子(在求最大共因子的时候可以选择把这条路径上的任意一点的权值置为0).对于每一个节点单 ...