Deploying a user service to another service in Angular 2

I want to add a service to another service. I have no problem implementing standard angular services (Http, etc.), but I get an exemption when I try to implement 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 tried using constructor(private anotherService: AnotherService) , still constructor(private anotherService: AnotherService) exception.

Thanks!

+5
source share
1 answer

You should read the Angular 2 documentation. Your exact problem 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 the providers array. The only reason you can use Http without this is because Ionic puts it in an array of providers for you. If you used vanilla Angular 2, you still have to add HTTP_PROVIDERS to the providers array.

As a side note, you don't need this Inject in your constructor, you can just do:

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

Source: https://habr.com/ru/post/1246240/


All Articles