Dynalon
Dynalon

Reputation: 6815

How to inject a Service into another Service in Angular2 >= 2.0.0-rc6?

Duplication note: Most questions + according answers to the same topic are based on Angular2 <= v2.0.0-rc4. With rc5 the old Module/Provider API was deprecated and in rc6 removed, so those answers don't apply anymore.

Question is: How do I inject an angular2 service into another service class? Singe Services are not @Component()s they don't have the "prodivers" metadata field. And in angular2 >= rc6 adding the service as a dependency into the bootstrap() function doesn't work anymore. So how to do it?

Upvotes: 1

Views: 423

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657048

All providers added to providers: [] of an @NgModule() are made available globally (except for lazy loaded modules). So if Service1 needs to inject Service2 this is enough:

@NgModule({
  providers: [Service1, Service2],
  // or
  imports: [SomeModule] // where `SomeModule` contains above providers
})
class AppModule {}

You can also add the providers to components.

@Component({
   providers: [Service1, Service2]
})

Upvotes: 2

Related Questions