Injection Context
- 顾名思义,注入上下文,说的通俗点,就是在Angular代码中,什么位置可以注入,比如我们最常用的constructor
就属于一个Injection Context
,因为你可以在constructor
中注入服务。
Angular支持的Injection Context
有如下几种:
- In class
constructor
- In the initializer for fields of such classes.
- In the factory function specified for useFactory of a Provider or an @Injectable
- In the factory function specified for an InjectionToken.
- Within a stack frame that runs in an injection context. - 这是个啥?我咋看不懂捏?
In class constructor
constructor
是我们最常用的注入位置,比如我们在组件中注入服务,就是在constructor
中注入的。
新的写法, 使用inject
函数
1 | export class AppComponent { |
旧的写法
1 | export class AppComponent { |
In the initializer for fields of such classes
这个是啥意思呢?就是在类的字段初始化器中,也可以注入服务,比如下面的DataService.
1 | export class AppComponent { |
Stack frame in an injection context
有些函数被设计成可以运行在injection context中,比如我们常用的路由守卫(router guard), 之所以这样是为了能让我们在路由守卫中注入服务。比如下面的canActivateTeam
函数,就是一个路由守卫。在这个函数里,我们可以注入PermissionsService
和UserToken
。这样就可以判断用户是否有权限访问某个页面。
1 | const canActivateTeam: CanActivateFn = |
Run within an injection context
有时候我们需要讲一个函数运行在injection context中,但是当前上下文并不是injection context
, 这时,我们可以使用runInInjectionContext
函数来创建一个新的injection context, 然后在这个新的injection context中运行我们的函数。
比如Angular框架要求effect
函数是必须运行在injection context
中,所以我们通常在构造函数体中运行effect
函数,如果我们想在ngOnInit
函数中运行effect
函数呢?因为ngOnInit
函数并不是injection context
, 这时我们就可以使用runInInjectionContext
函数来运行effect
函数。
注意:使用runInInjectionContext
函数需要一个EnvironmentInjector
1 | export class CountComponent implements OnInit { |