0

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?

Cequiel
  • 3,505
  • 6
  • 27
  • 44

1 Answers1

4

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.

Shlomi Assaf
  • 2,178
  • 18
  • 19
  • Thanks for your answer. It was what I suspected. I wonder what is the purpose of the @Inject() directive, since it can be omitted and it does nothing. – Cequiel Jul 10 '16 at 20:13
  • 1
    The `@Inject` decorator allows (among other things) injection of string tokens (opposed to type tokens), see OpaqueToken. Also note that when you declare `@Injectable` on a class you tell tell the Injector that this class can be injected, making the `@Inject` redundant for Typed Tokens (you still need it for String tokens) – Shlomi Assaf Jul 11 '16 at 08:48