[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框架搭建是从小米手机公司内个整个流程方面来考虑,如何提高效率生产效率,这篇博客主要从公司外部环境说明如何提高生产效率,那么怎么才能提高 ...
随机推荐
- 在 C# 中通过 P/Invoke 调用Win32 DLL
在 C# 中通过 P/Invoke 调用Win32 DLL 发布日期 : 1/13/2005 | 更新日期 : 1/13/2005 Jason Clark 下载本文的代码: NET0307.exe ( ...
- python中的迭代器详解
#原创,转载请先联系 理论性的东西有点枯燥,耐心点看- 1.迭代是什么? 我们知道可以对list,tuple,dict,str等数据类型使用for...in的循环语法,从其中依次取出数据,这个过程叫做 ...
- 工作管理 (job control)
这个工作管理 (job control) 是用在 bash 环境下的,也就是说:『当我们登入系统取得创建的 bash shell 进程之后,在该bush下同时进行多个工作的行为管理 』. 而所有创建的 ...
- 记一次Laravel定时任务导致日志没有写入权限的坑
问题:用laravel开发定时任务时,发生了日志没有写入权限导致项目打不开的问题 原因:linux的添加定时任务时默认是当前登录用户,我定时任务会生成日志 crontab: kernel: 生成日志的 ...
- [BZOJ1492] [NOI2007]货币兑换Cash 斜率优化+cdq/平衡树维护凸包
1492: [NOI2007]货币兑换Cash Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 5907 Solved: 2377[Submit][Sta ...
- hdu5076
好题,首先观察可得w[i][j]选择只有可能两种,一种比阀值大,一种比阀值小 比阀值大就一定选满足条件最大的w,比阀值小同样一定选满足条件最大的w 那么一个最小割模型就呼之欲出了,注意w可能是负数那么 ...
- [centos6.5] 把xampp的htdocs改为其他目录
vim /opt/lampp/etc/httpd.conf DocumentRoot "/opt/lampp/htdocs" 改为 DocumentRoot "/var/ ...
- (11)python 模块和包
一.导入模块和包 模块相当于一个.py文件,包相当于带有个__init__.py一个文件夹,既可按模块导入也可按包导入. 1.导入模块或包 import 包名或模块名 (as 别名),包名或模块名 ( ...
- 欧拉图和欧拉圈-Play On Words(UVa10129)
欧拉路和欧拉圈,简言之就是,从无向图的一个结点出发,走一条路/圈,每条边恰好经过一次,即一笔画问题 欧拉定理:一个无向图最多只有两个奇结点,那么我们就从一个奇结点出发,到另一个结点为之,一定有一条欧拉 ...
- hdu6138(后缀数组)
hdu6138 题意 给出若干个字符串,每次查询两个字符串,求两个字符串的公共子串且在给出的某一个字符串中作为前缀的最大长度. 分析 求公共子串:后缀数组 判断前缀:字典树 求完后缀数组,遍历下 \( ...