2016-04-01 8 views
5

Chcę wprowadzić usługę do innej usługi. Nie mam żadnych problemów z wstrzykiwaniem standardowych usług kątowych (Http, itp.), Ale dostaję wyjątek, gdy próbuję wstrzykiwać własne usługi.Wstrzyknij niestandardową usługę w innej usłudze w Angular 2

Przykład:

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'); } 

} 

Kiedy próbuję użyć MyService mam EXCEPTION: No provider for AnotherService!

Próbowałem została, używając constructor(private anotherService: AnotherService), nadal wyrzuca wyjątek.

Dzięki!

Odpowiedz

5

Powinieneś przeczytać dokumentację Angular 2. Dokładny problem został wyjaśniony w kątowych dokumentach tutaj: https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service

Musisz dodać swoją usługę do tablicy dostawców. Jedynym powodem, dla którego możesz używać Http, nie robiąc tego, jest to, że Ionic umieszcza go w tablicy dostawców dla ciebie. Jeśli używasz wanilii Angular 2, nadal będziesz musiał dodać HTTP_PROVIDERS do tablicy providerów.

Na marginesie, nie trzeba, że ​​inject konstruktora, można po prostu zrobić:

constructor(private anotherService: AnotherService) { 
    console.log(this.anotherService.get()); 
} 
+0

Dziękuję bardzo! Teraz działa! Podałem właśnie 'AnotherService' w dostawcach składników. Powinienem uważniej czytać dokumenty. – NoName

Powiązane problemy