wtorek, 4 kwietnia 2017

Angular2 - Two ways of injecting dependencies

There are two ways of delivering dependencies to the created object. One is the widely know "injection by type", which is done by specifying typed parameters in constructor.

Inject by Type

constructor(private service: MyService) {
}
This assumes MyService is imported specific class put into providers of your module.

Inject by Name

Another way is "injecting by name".

constructor(@Inject('myService') private service) {
}
This time we required the following in the module providers list
{provide: 'myService', useClass: MyService},
The main advantage of the latter is we actually get rid of importing specific class, though, decouple from other local resources

We can also provide values instead of classes:

{provide: 'url', useValue: 'http://localhost'},

Brak komentarzy:

Prześlij komentarz