神刀安全网

Providers inheritance and overriding in Angular 2

This week I’ve attend Thoughtram’s Angular 2 training in Dusseldorf (great course by the way). At one point during the exercises I started to have some weird behavior on my application. A lot of this was related to the way Angular 2 is treating now the providers.

Let’s say we have a AppService that is shared by all the components in our application. Angular 2 makes it quite easy to create and inject a service into our components. First we will need to create a simple class that will become our service. In the end Angular 2 services are just plain classes:

export class AppService {   public data = "default value"; }
export class AppService {   public data = "default value"; } 

Please keep in mind that, if you are using Typescript and if our service was depending of some other service, eg: Http, we will have to enhance that service with the @Inject decorator. More details about this here .

In order to inject this very simple service into our components we will have to import and declare it in the providers array property . After this we can inject it in the constructor of the component:

import {AppService} from './services/app-service';  //...  @Component({    providers: [AppService],    //... )} class App {     constructor(private appService:AppService) {       appService.data = "value set by the App Component";       this.componentData = appService.data;     } }
import {AppService} from './services/app-service';   //...   @Component({   providers: [AppService],   //... )} class App {     constructor(private appService:AppService) {       appService.data = "value set by the App Component";       this.componentData = appService.data;     } } 

Now the AppComponent and all of it’s children will use the same instance of the AppService . Basically the children of a component will inherit that component’s providers.

But keep in mind that this provider can also be overwritten. If we declare a new provider of the AppService type in the providers array of a sub-component, that component and all of it’s children will use a brand new instance of that provider! In our example this is the case of ComponentTwo:

import {Component} from 'angular2/core'; import {AppService} from '../services/app-service';  @Component({   //...   providers: [AppService] })
import {Component} from 'angular2/core'; import {AppService} from '../services/app-service';   @Component({   //...   providers: [AppService] }) 

This mechanism of providers in Angular 2, can lead to great advantages given the fact that we can enhance a specific component service. But if not treated with care, can also lead to great confusion. For example if you accidentally overwrite a Provider you will get a new created instance, with the default data.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Providers inheritance and overriding in Angular 2

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮