首页 > 代码库 > [Angular 2] BYPASSING PROVIDERS IN ANGULAR 2

[Angular 2] BYPASSING PROVIDERS IN ANGULAR 2

Artical --> BYPASSING PROVIDERS IN ANGULAR 2

 

Here trying to solve one problem:

技术分享

On the left hand side of tree, there are 4 green blocks and 1 blue block. 

Meaning that three green dataService will use ‘OtherProvider‘ which in an instance of DataService, but different from the root Provider, even it is also a instance of DataService.

 

Problem is how the blue one on the left can use the root provider instead of ‘OtherProvider‘.

 

Creating alias tokens with useExisting

@NgModule({  ...  providers: [    DataService,    { provide: ROOT_DATASERVICE, useExisting: DataService }  ]})export class AppModule {}
import { OpaqueToken } from ‘@angular/core‘;export const ROOT_DATASERVICE = new OpaqueToken(‘DataService‘);

We create a new provider call ‘RootDataServcie‘ and using ‘useExisting‘ key. And we use OpaqueToken to avoid naming conflicts.

 

In the component:

@Component()export class SomeComponent {    constructor(private contactService: RootDataService) {}}

 

[Angular 2] BYPASSING PROVIDERS IN ANGULAR 2