zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular 2] BYPASSING PROVIDERS IN ANGULAR 2

Angular in
2023-09-14 08:59:19 时间

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