Angular:ViewProviders和Providers的区别
在Angular中使用依赖注入(DI)的时候,我们一般会使用providers。其实要做同样的事我们还有另外一个选择:viewProviders。
viewProviders允许我们定义只对组件的view可见的provider。下面我们用例子详细的说明这一点。
假设我们有一个简单的服务:
// myService.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MyService{
testIfGetService(where){
console.log('Got My Service in ' + where);
}
}
这个服务很简单,只需要打印出在哪里调用了该服务。
然后有一个子组件,是用来投射到父组件里面的(等会将会看到):
// child.component.ts
import { Component } from '@angular/core';
import { MyService } from './myService.service';
@Component({
selector: 'vp-child',
template: `
<div>This is child!!!</div>
`
})
export class VPChild{
constructor(
private service: MyService
){
this.service.testIfGetService('child');
}
}
这个组件注入了MyService服务,调用MyService的testIfGetService方法,并传入child表明这是在child组件调用的。
还有另外一个子组件,这个组件是用来放在父组件的模板(template)里面的:
// viewChild.component.ts
import { Component } from '@angular/core';
import { MyService } from './myService.service';
@Component({
selector: 'vp-viewchild',
template: `
<div>This is viewChild!!!</div>
`
})
export class ViewVPChild{
constructor(
private service: MyService
){
this.service.testIfGetService('viewChild');
}
}
这里同样注入MyService服务,调用MyService服务的testIfGetService方法,并传入viewChild。
最后是父组件:
// parent.component.ts
import { Component } from '@angular/core';
import { MyService } from './myService.service';
@Component({
selector: 'vp-parent',
template: `
<div>This is parent!!!</div>
<ng-content></ng-content>
<vp-viewchild></vp-viewchild>
`,
providers: [MyService]
})
export class VPParent{
constructor(
private service: MyService
){
this.service.testIfGetService('parent');
}
}
在父组件,用providers注册MyService,然后调用MyService的testIfGetService传入parent。
然后就像这样使用父组件:
<vp-parent>
<vp-child></vp-child>
</vp-parent>
运行程序,控制台打印出了结果:

一切就像预期那样!!
然后,我们用viewProviders代替providers注册MyService,看看会发生什么:
// parent.component.ts
import { Component } from '@angular/core';
import { MyService } from './myService.service';
@Component({
selector: 'vp-parent',
template: `
<div>This is parent!!!</div>
<ng-content></ng-content>
<vp-viewchild></vp-viewchild>
`,
viewProviders: [MyService] // <---
})
export class VPParent{
constructor(
private service: MyService
){
this.service.testIfGetService('parent');
}
}
这样修改之后,运行程序,发现报错了:

如果把contentChild注释掉,就像这样:
<vp-parent>
<!-- <vp-child></vp-child> -->
</vp-parent>
是不会报错的:

这就说明,在父组件用viewProviders注册的provider,对contentChildren是不可见的。而使用providers注册的provider,对viewChildren和contentChildren都可见!
补充说明:组件会逐级向上寻找provider,直到找到为止,否则就会抛出错误。就像这里:
<vp-parent>
<vp-child></vp-child>
</vp-parent>
vp-child往上找MyService的provider,结果在vp-parent找到了。但是在用viewProviders的时候,vp-child往上找,也就是到vp-parent,结果没找到,然后又去找vp-parent的父级,还是没找到(因为在这个例子里,我们只在vp-parent注册了MyService),然后又继续往上找……如此找到边界也没找到,所以抛出了一个错误。如果你不希望这样,可以使用@Host做出限制,就像这样:
constructor(
@Host() private service: MyService
){}
关于@Host()本文不作展开,有兴趣可以自行google。
Angular:ViewProviders和Providers的区别的更多相关文章
- [Angular] Difference between Providers and ViewProviders
For example we have a component: class TodoList { private todos: Todo[] = []; add(todo: Todo) {} rem ...
- [Angular 2] Value Providers & @Inject
Dependecies aren’t always objects created by classes or factory functions. Sometimes, all we really ...
- [Angular 2] BYPASSING PROVIDERS IN ANGULAR 2
Artical --> BYPASSING PROVIDERS IN ANGULAR 2 Here trying to solve one problem: On the left hand s ...
- [Angular] Pipes as providers
In this example, we are going to see how to use Pipe as providers inject into component. We have the ...
- angular $observe() 和$watch的区别
1.$observe()是属性attributes的方法,只能在DOM属性的值发生变化时用,并且只用于directive内. 当需要监听一个包含变量的属性值时attr1="Name:{{na ...
- angular js jquery中post请求的一点小区别
这也是最近遇到的坑,还是之前那个项目,现在要实现登录功能. 背景:注册功能之前已经跑通了.前端用的是jquery后台是springMVC.鉴于注册和登录有些接口功能是类似的(比如注册确保邮箱是没有注册 ...
- angular学习—组件
组件: vue组件:xxx.vue react组件:xxx.js+xxx.css angular组件:xxx.ts+xxx.css+xxx.html angular的装饰器: @ngModule:an ...
- quora 中有关angular与emberjs的精彩辩论
原贴地址,要注册才能看,这里只有国人翻译的一部分内容 本文源自于Quora网站的一个问题,作者称最近一直在为一个新的Rails项目寻找一个JavaScript框架,通过筛选,最终纠结于Angular. ...
- Angular.js vs Ember.js
Angular.js 拥抱 HTML/CSS Misko Hevery(Angular.js的开发者之一)回答了这一问题,他的主要观点如下: 在HTML中加入太多逻辑不是好做法.Angular.js只 ...
随机推荐
- python-笔记-内置函数
###内置函数 print(all([1,2,3,4]))判断可迭代的对象里面的值是否都为真 print(any([0,1,2,3,4]))判断可迭代的对象里面的值是否有一个为真 print(id(l ...
- Android Framework中Thread类
Thread类是Android为线程操作而做的一个封装.代码在Thread.cpp中,其中还封装了一些与线程同步相关的类. Thread类 Thread类的构造函数中的有一个canCallJava T ...
- vue组件的watch属性
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- 《Selenium 2自动化测试实战 基于Python语言》中发送最新邮件无内容问题的解决方法
虫师的<Selenium 2自动化测试实战 基于Python语言>是我自动化测试的启蒙书 也是我推荐的自动化测试入门必备书,但是书中有一处明显的错误,会误导很多读者,这处错误就是第8章自动 ...
- 【ABAP系列】SAP WEB GUI的实现,SAP在网页中使用
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP WEB GUI的实现,SAP ...
- c++中关于类的长度的猜想
在无意中,我偶然发现了类的长度并不是由函数的类型及个数决定,也并非是2的倍数.4的倍数. 在翻阅资料中,我得出了一些我认为可能的猜想. 我们先来看一串代码 #include<iostream&g ...
- 【洛谷p1314】聪明的质监员
聪明的质监员[题目链接] 有关算法: 二分答案: 但是你只二分答案是不够的,因为你check会炸,所以还要考虑前缀和: 首先假装我们的check已经写好了,main函数: int main() { n ...
- Linux查看当前目录下所有文件中包含map的行记录
find yaochi_e.prm |xargs grep -ri "map" grep -n "map" *.prm|grep -v "\-\-ma ...
- python学习笔记(7): 面向对象
class Foo: #类中的函数 def bar(self): #功能阐述 print('Bar') pass def hello(self,name): print('i am %s' %name ...
- Javascript | DOM\DOM树浅析
DOM Document Object Model(文档对象模型) 定义了表示和修改文档所需的方法. DOM对象即为宿主对象,由浏览器厂商定义,用来操作html和xml功能的一类对象的集合.也有人称D ...