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 】三大主流软件负载均衡器对比(LVS、Nginx、HAproxy)

    三大主流软件负载均衡器对比(LVS.Nginx.HAproxy) (资料来自网络,做了部分的补充说明) LVS:    1. 抗负载能力强,性能高,能达到F5的60%,对内存和CPU资源消耗比较低   ...

  2. redis使用管道pipeline提升批量操作性能(php演示)

    Redis是一个TCP服务器,支持请求/响应协议. 在Redis中,请求通过以下步骤完成: 客户端向服务器发送查询,并从套接字读取,通常以阻塞的方式,用于服务器响应. 服务器处理命令并将响应发送回客户 ...

  3. 【转载】bash: ifconfig: command not found 解决办法

    原本使用ifconfig 可以使用,今天是怎么了,可能安装软件修改了,百度~~ [oracle@localhost /]$ ifconfig 提示:“bash: ifconfig: command n ...

  4. CvScalar

    CvScalar定义可存放1—4个数值的数值,其结构如下. typedef struct CvScalar{    double val[4];}CvScalar; ----------------- ...

  5. HDU 1285 确定比赛名次【字典序最小的拓扑排序 + 优先队列】

    确定比赛名次 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submis ...

  6. 洛谷 P2415 集合求和【数学公式/模拟】

    给定一个集合s(集合元素数量<=30),求出此集合所有子集元素之和. 输入输出格式 输入格式: 集合中的元素(元素<=1000) 输出格式: 和 输入输出样例 输入样例#1: 2 3 输出 ...

  7. Maven学习笔记2

    Maven安装配置 1.下载Maven 官方地址:http://maven.apache.org/download.cgi 将下载的压缩包解压到你要安装 Maven 的文件夹.假设你解压缩到文件夹 – ...

  8. 1.6(学习笔记)Session

    一. Session简介 Session是用于解决HTTP无状态问题,HTTP协议本身是没有状态的, 就类似一个没有记性的商人,每次只交易当前的货物,交易完后就忘记了 以前的交易历史.我们和商人交易时 ...

  9. 10.1(java学习笔记)JDBC基本操作(连接,执行SQL语句,获取结果集)

    一.JDBC JDBC的全称是java database connection java数据库连接. 在java中需要对数据库进行一系列的操作,这时就需要使用JDBC. sun公司制定了关于数据库操作 ...

  10. 排排看(p20)

    public class paixu{public static void main(String[] args){int x=3;if(x>2){System.out.print(" ...