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) {}
}

Lesson

[Angular] Control the dependency lookup with @Host, @Self, @SkipSelf and @Optional的更多相关文章

  1. [Angular] Component's dependency injection

    An Angular service registered on the NgModule is globally visible on the entire application. Moreove ...

  2. [Angular Tutorial] 7-XHRs & Dependency Injection

    我们受够了在应用中用硬编码的方法嵌入三部电话!现在让我们用Angular内建的叫做$http的服务来从我们的服务器获取更大的数据集吧.我们将会使用Angular的依赖注入来为PhoneListCtrl ...

  3. [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, ...

  4. 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 ...

  5. angular(常识)

    我觉得angularjs是前端框架,而jquery只是前端工具,这两个还是没有可比性的. 看知乎上关于jquery和angular的对比http://www.zhihu.com/question/27 ...

  6. Angular 4+ 修仙之路

    Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...

  7. Dependency Injection

    Inversion of Control - Dependency Injection - Dependency Lookup loose coupling/maintainability/ late ...

  8. Hosting custom WPF calendar control in AX 2012

    原作者: https://community.dynamics.com/ax/b/axilicious/archive/2013/05/20/hosting-custom-wpf-calendar-c ...

  9. Spring (一) IOC ( Inversion Of Control )

    前序 现在小米手机很火就还拿小米手机来举例子,上一篇写的关于SSH框架搭建是从小米手机公司内个整个流程方面来考虑,如何提高效率生产效率,这篇博客主要从公司外部环境说明如何提高生产效率,那么怎么才能提高 ...

随机推荐

  1. Linux添加用户并赋予/取消管理员权限

    Ubuntu sudo adduser username # 添加用户 sudo adduser username sudo # 追加管理员权限 grep -Po '^sudo.+:\K.*$' /e ...

  2. springmvc formatter

    以下,来自于Springmvc指南第二版,第93页. Spring的Formatter是可以将一种类型转为另一种类型. 例如用户输入的date类型可能有多种格式. 下面是才用 registrar方式注 ...

  3. 【转】JSP自定义标签

    转载自:http://www.cnblogs.com/edwardlauxh/archive/2010/05/20/1918587.html tld标签的描述文件 标签的描述文件是一个描述整个标签库标 ...

  4. V-Hyper安装ubuntu-13.10-server-amd64

    1.在windws8上的V_Hyper虚拟机上安装Ubuntu虚拟机服务器版.遇到的问题和解决方案 2.正确的在V-Hyper配置方法参考文章:在Hyper-V中安装和配置Ubuntu Server ...

  5. [ Python - 9 ] 高阶函数map和reduce连用实例

    1. 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456: from functools import reduce def str2num( ...

  6. 《Java编程思想》笔记 第六章 访问权限控制

    1.编译单元 一个 编译单元即 .java 文件 内只能有一个 public 类  且该文件名必须与public 类名 完全一致. 编译单元内也可以没有public类 文件名可随意. 2. 包:库单元 ...

  7. selenium java 读取xml (数据驱动)

    selenium 数据驱动 (xml解析) getElementByTagName()可以通过标签名获取某个标签.它所获取的对象是以数组形式存放.如“caption”和“item”标签在info.xm ...

  8. python-函数(命名空间、作用域、闭包)

    一.命名空间 全局命名空间 局部命名空间 内置命名空间 *内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就 ...

  9. hdu 5190(水题)

    Go to movies Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Tota ...

  10. Laravel开启跨域的方法

    1.建立中间件Cors.php 命令:php artisan make:middleware Cors 在/app/Http/Middleware/ 目录下会出现一个Cors.php 文件. 内容如下 ...