[Angular 2] DI in Angular 2 - 1

本文详细介绍了 Angular 2 中依赖注入(DI)的工作原理,对比了 Angular 1 的 DI 不足之处,并深入探讨了如何通过不同的配置解决单例和服务实例化的问题,包括使用 useClass、useValue、useExisting 和 useFactory 等方法。

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

 

转载于:https://www.cnblogs.com/Answer1215/p/5576367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值