I want to inject service into another service. I don't have any problems injecting standard angular services (Http, etc.), but I get an exeption when I am trying to inject my own services.
Example:
MyService:
import {Injectable, Inject} from 'angular2/core';
import {AnotherService} from '../../services/another.service';
@Injectable()
export class MyService {
constructor(Inject(AnotherService) private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
}
AnotherService:
import {Injectable} from 'angular2/core';
@Injectable()
export class AnotherService {
constructor() { }
get() { return 'hello'); }
}
When I try to use MyService I get EXCEPTION: No provider for AnotherService!
I've tried using constructor(private anotherService: AnotherService)
, still throws an exception.
Thanks!
Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.
Use the @Injectable() decorator on any service that depends on another. Inject the other services into the constructor of the dependent service.
We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.
There are three types of Dependency Injections in Angular, they are as follows: Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency.
You should read the Angular 2 documentation. Your exact issue is explained in the angular docs here: https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service
You must add your service to a providers array. The only reason you can use Http without doing this is because Ionic puts it on the providers array for you. If you were using vanilla Angular 2 you would still have to add HTTP_PROVIDERS to the providers array.
As a side note, you don't need that Inject in your constructor, you can just do:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With