AngularJS 2 Provider

Source: Internet
Author: User

Dependency Injection (DI) is the core of Angular 2, and before we dive into the workings of DI, we must first understand the concept of Provider.

In Angular 2 We use Provider to describe how the dependent objects associated with tokens are created. There are four ways to create dependent objects in Angular 2, respectively:

    • Useclass

    • Usevalue

    • Useexisting

    • Usefactory

Useclass

 @Injectable () Export class apiservice {   constructor (           public http: Http,            public loadingctrl: loadingcontroller)  {   }       &NBSP, ...}      @NgModule ({  ...      providers: [       //  can use concise syntax, that is, direct use of apiservice    { provide:  apiservice, useclass: apiservice }  ]}) export class coremodule {  }

Usevalue

{provide: ' Api_url ', Usevalue: ' Http://my.api.com/v1 '}

Useexisting

{provide: ' Apiservicealias ', useexisting:apiservice}

Usefactory

export function configfactory (Config: appconfig)  {       return  ()  => config.load ();} @NgModule ({      ...    providers: [      { provide: app_initializer, usefactory: configfactory, deps: [ appconfig],         multi: true }  ]}) Export  class coremodule { } 

Use the correct posture of Provider

1. Create Token

Token is used to identify a dependent object, and the token value may be an instance of type, Injectiontoken, Opaquetoken class, or a string. It is generally not recommended to use strings, because there is a high likelihood of naming conflicts if strings are used. In previous versions of Angular 4.x, we used Opaquetoken to create tokens, and Injectiontoken was recommended to create tokens in Angular versions above 4.x. Detailed content can refer to, how to resolve Angular 2 in the Provider naming conflict.

2. Choose how dependent objects are created based on actual requirements, such as Useclass, Usevalue, useexisting, usefactory

3. Register in Ngmodule or Component providers

4. Injecting dependent objects associated with tokens using a construction injection

The/***  encapsulates the HTTP service, such as adding tokens to each HTTP request header, similar to interceptors in ng1.x */@Injectable ()  export class apiservice  {       constructor (           //  inject HTTP service in angular 2 , the difference from ng1.x:          //  after invoking the HTTP service in ng1.x, return the Promise object          //  After invoking the HTTP service in ng2.x, the observable object is returned             public  http: http)  {    }  &nbsp ...}       /*** appmodule*/@NgModule ({     //  You can use the concise syntax, which is to use Apiservice ...  providers: [{ provide: apiservice, useclass directly:  apiservice } ]}) export class appmodule { }/***  System home */@Component ({       selector:  ' Page-home ', &Nbsp;   templateurl:  ' home.html '}) export class homepage {       constructor (         //  using the construction injection method, An instance object that injects Apiservice          public apiservice: apiservice )  { }           ngoninit ():  void {            //  get home-related data         this.apiservice.get (Home_url)        .map (res =>  res.json ())  //  The returned Res object is an instance of the response type        .subscribe ( result => {                  ...          })       }}

I have something to say.

1. When di parses the Providers, each of the provided provider is normalized and converted into a standard form.

Function _normalizeproviders (providers: provider[],     res: provider[ ]):  provider[] {     providers.foreach (b => {          if  (B instanceof type)  { //  supports concise syntax, Convert to standard format                  Res.push ({provide: b, useclass: b});           }       else if  (b && typeof b  ==  ' object '  &&  (b as any). provide !== undefined)        {            res.push (B as  normalizedprovider);          }        else if  (B instanceof array)  {              _normalizeproviders (b, res); //  If it is an array, recursive processing           } else {                 throw invalidprovidererror (b);           }      });           return res;}

2. To avoid naming conflicts, try to avoid using strings as tokens when creating tokens.

3. To create a generic dependent object within a module, you need to register the relevant provider in Ngmodule, and if you have a unique dependent object in each component, you need to register the associated provider in Component.

4.multi providers specific function, please refer to-Angular2 multi providers

5.Provider is used to describe how the dependent objects associated with tokens are created. When we use Token to get a dependent object associated with the DI system, Di automatically creates the dependent object and returns it to the consumer based on how it was created.

Provider Interface

export interface classprovider {  //  is used to set the token value associated with the dependent object, the token value may be type, Instances or strings of Injectiontoken, opaquetoken//        provide: any;        useClass: Type<any>;      //  Used to identify whether multiple providers, if multiple type, returns a list of dependent objects associated with token       multi?:  Boolean; }export interface valueprovider {      provide:  any;      usevalue: any;      multi?:  boolean;}  export interface ExistingProvider {      provide: any;       useExisting: any;      multi?:  Boolean;}  export interface FactoryProvider {      provide: any;       usefactory: function;      deps?: any[];   //  dependent object       multi?: boolean for setting the factory function;}

Summarize

At the end of the article, I want to give a real-life example to help beginners better understand Angular 2 DI and Provider.

Providertokencan be understood as the name of the dish, Useclass, usevalue can be understood as the cooking of the dish, and the dependent object is what we ordered, and DI system is our chef. If there is no chef, we have to care about what raw materials to cook this dish, how to cook, the important thing is to cook, can imagine more trouble. And with the chef (DI), we just order on the menu, if necessary, note the way of cooking, but how long the delicious food on the table bird ~ ~ ~.


AngularJS 2 Provider

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.