Angular 2 - Create Service A

Background

We create an Angular2 application and accumulate many specific services related to one module. All of these services are loosely coupled to the event system Subject<Type>in the application.

Activation through the constructor

Since these services never directly refer and subscribe only to events, we just need to create them somehow. For the time being, we are simply injecting them into the constructor of another service that is being used.

// Services not used, just to make sure they're instantiated
constructor(
  private appService1: AppService1,     
  private appService2: AppService2,
  private appService3: AppService3,
  ...
){ }

This seems like a hack, is there a better way to explicitly provide the services that you need to create without inserting them through the constructor?

+4
source share
2 answers

, ,

// app.module.ts

@NgModule({
  providers: [
    { provide: AppService1, useValue: new AppService1() },
    { provide: AppService2, useValue: new AppService2() },   
    { provide: AppService2, useValue: new AppService3() }
  ]
}) export class AppModule {}

, , , DI .

, ES TypeScript , SystemJS.

, , , , , . , .

, , , , useValue, useFactory. , , .

+2

.

, , , .

:

.

@NgModule ({
    providers: [ myservice1, myservice2],
})

.

, . , , , , . .

, , , .

@Component ({
     providers: [myservice]
})

.

+1

Source: https://habr.com/ru/post/1664122/


All Articles