[Angular 2] DI in Angular 2-1

Source: Internet
Author: User

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 is differnet with the one you inject to child component:

var injector = reflectiveinjector.resolveandcreate ([Engine]); var childinjector =!== childinjector.get (Engine);

' Resolveandcreate ' & ' Resolveandcreatechild ' is function to create injector.

Even here and the same service ' Engine ', but the instances is different.

In Angular2, it looks like:

// Child Component @Component ({  ' child ',  providers: [Engine],  ' }) Class child{...  } // parnet Component @Component ({  ' parent ',  providers: [Engine],  ' }) class Parent {  ...}

The ' Engine ' we inject into child component are a new instance, which is not the same as parent one.

So, if we want to share the same instance?

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

So in code, it'll looks like:

// Child Component @Component ({  ' child ',  providers: [],  ' }) class child{...  } // parnet Component @Component ({  ' parent ',  providers: [Engine],  ' }) 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: () = {  returnfunction  () {    if (IS_V8) {      returnnew  v8engine ();     Else {      returnnew  v6engine ();}}}  )

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

provide (engine, {  = = {  },  deps: [Car, Engine]})

[Angular 2] DI in Angular 2-1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.