[Angular 2] DI in Angular 2 - 1

Orgial aritial --> Link

 

The problem with Angular 1 DI:

 

Angular 2 DI:

  • Solve the singletons problem:

The service you inject to the parent component can be differnet with the one you inject to child component:

var injector = ReflectiveInjector.resolveAndCreate([Engine]);
var childInjector = injector.resolveAndCreateChild([Engine]);

injector.get(Engine) !== childInjector.get(Engine);

`resolveAndCreate` & `resolveAndCreateChild` are function to create injector.

Even here use the same service `Engine`, but the instances are different.

 

In Angular2, it looks like:

复制代码
// child component
@Component({
  selector: 'child',
  providers: [Engine],
  template: '<h1> childcomponent !</h1>'
})
class Child{
  ...
}


// parnet component
@Component({
  selector: 'parent',
  providers: [Engine],
  template: '<h1> parent component !</h1>'
})
class Parent {
  ...
}
复制代码

The `Engine` we inject into Child component is a new instance, which is not the same as parent one.

 

So what if we want to share the same instance?

 

Well, If child component and parent component want the same service, then we only inject servie to parent component. The child component can access parent component's injected service.

So in code, it will looks like:

复制代码
// child component
@Component({
  selector: 'child',
  providers: [],
  template: '<h1> childcomponent !</h1>'
})
class Child{
  ...
}


// parnet component
@Component({
  selector: 'parent',
  providers: [Engine],
  template: '<h1> parent component !</h1>'
})
class Parent {
  ...
}
复制代码

We just remove 'Engine' from Child component, now they share the same service instance.

 

  • Solve name collision problem:

Angular 2 allows you configure the service differently:

  1.  useClass:
provide(Engine, {useClass: OtherEngine})

  2. useValue:

provide(String, {useValue: 'Hello World'})

  3. useExisting:

provide(V8, {useExisting: Engine})

  4. useFactory:

复制代码
provide(Engine, {useFactory: () => {
  return function () {
    if (IS_V8) {
      return new V8Engine();
    } else {
      return new V6Engine();
    }
  }
}})
复制代码

Of course, a factory might have its own dependencies. Passing dependencies to factories is as easy as adding a list of tokens to the factory:

provide(Engine, {
  useFactory: (car, engine) => {

  },
  deps: [Car, Engine]
})

 

posted @   Zhentiw  阅读(243)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示