Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject custom service in another service in Angular 2

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!

like image 700
NoName Avatar asked Apr 01 '16 13:04

NoName


People also ask

Can I inject a service into another service Angular?

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.

What is the best way to inject one service into another in Angular?

Use the @Injectable() decorator on any service that depends on another. Inject the other services into the constructor of the dependent service.

What is difference between @inject and @injectable in Angular?

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.

How many ways we can inject service in Angular?

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.


1 Answers

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());
}
like image 97
Rob Louie Avatar answered Oct 23 '22 14:10

Rob Louie