Inject a service into another service

2019-09-13 02:18发布

问题:

I would like to inject a service into another service but, for some reason, the "@Inject" decorator is being ignored. For example, the following service depends on another service:

@Injectable()
class MyService {
    final AnotherService _service;
    MyService(@Inject(AnotherService) this._service);
// ... more methods
}

Angular2 throws the following error:

ORIGINAL EXCEPTION: No provider for AnotherService!

Am I using the "@Inject" decorator in a bad way?

回答1:

Some information is missing to fully solve this but exception says that the injector doesn't have enough information to resolve AnotherService

The DI in angular is build upon hierarchies, starting from the root injector which is created upon an angular application bootstrap.

Each hierarchy is a new injector instance, resolving a dependency is done from bottom to top, i.e: if an injector can't resolve it will ask its parent to resolve. This will go on until it reach an injector without a parent (root injector).

Make sure you declare a provider for AnotherService before you declare a provider for MyService.

Just add a provider to AnotherService in the providers array you supply to bootstrap.