[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框架搭建是从小米手机公司内个整个流程方面来考虑,如何提高效率生产效率,这篇博客主要从公司外部环境说明如何提高生产效率,那么怎么才能提高 ...
随机推荐
- flask+gunicorn中文文件下载报错问题及解决
导言 问题源起与一个静态文件下载的接口: from flask import Flask, current_app app = Flask(__name__) @app.route('/file_na ...
- celery-分布式任务队列-原理
# 转自:https://www.cnblogs.com/forward-wang/p/5970806.html 在学习Celery之前,我先简单的去了解了一下什么是生产者消费者模式. 生产者消费者模 ...
- 《JAVA8实战》读书笔记之传递方法和传递lambda
传递方法: 假设 你有一个Apple类,它 有一个getColor方法,还有一个变量inventory保存着一个Apples的列表.你可能想要选出所 有的绿苹果,并返回一个列表.通常我们用筛选(fil ...
- 开发者应该了解的API技术清单!
英文原文:API-Driven Development 作为一名开发者,诚然编写代码如同作家提笔挥毫,非常有成就感与乐趣,但同时我也觉得删除代码是件不相伯仲的美事.为什么呢?因为在进行删除工作时,意味 ...
- Windows server 2012 R2 环境搭建
由于系统升级,现在在用dotnetcore开发项目,但是尴尬的是服务器是windows server2012 R2的版本,这个版本不能执行dotnetcore. 然后问题来了,运行环境搭建. 第一步自 ...
- (八)MySQL索引操作
(1)准备环境 mysql> create table t1(id int,name varchar(50)); mysql> \d $$ mysql> create procedu ...
- centos6.5 403 Forbidden 设置了777还是不行
Forbidden You don't have permission to access /liuyanben/install on this server. Apache/2.2.15 (Cent ...
- Windows7 SP1旗舰版精简版最终版本
2016年6月9号,老毛子@lopatkin大神针对Win7 SP1旗舰版精简版进行了最终更新,此次主要是之前小问题的修复和调整.该版为Windows 7 SP1 简体中文旗舰版最新版,包含2016年 ...
- 洛谷 P2678 跳石头【经典二分答案/贪心】
题目描述 这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石.组委会已经选择好了两块岩石作为比赛起点和终点.在起点和终点之间,有 NN 块岩石(不含起点和终点的岩石).在比赛过程中,选手们将从 ...
- IBM-Club IntelliJ IDEA 开发环境的安装
各位小伙伴初次使用IDE,可能还是有许多疑惑,因此这篇博客阿鲁给大家分享一下,自己平时是如何安装IntelliJ IDEA的 1.原料:安装包,直接百度搜索进入官网下载 记住是Ultimate版本呦, ...