在Angular 2中的另一个服务中注入自定义服务

Inject custom service in another service in Angular 2

本文关键字:服务 注入 自定义 另一个 Angular      更新时间:2023-10-24

我想将服务注入另一个服务。我在注入标准角度服务(Http等)时没有任何问题,但当我尝试注入自己的服务时,我会得到一个exeption。

示例:

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

当我尝试使用MyService时,我会得到EXCEPTION: No provider for AnotherService!

我尝试过使用constructor(private anotherService: AnotherService),但仍然抛出异常。

谢谢!

您应该阅读Angular 2文档。您的确切问题在这里的角度文档中有解释:https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-服务需求服务

您必须将服务添加到提供程序阵列中。您可以在不执行此操作的情况下使用Http的唯一原因是Ionic将其放在提供者数组中。如果您使用的是vanilla Angular 2,那么您仍然需要将HTTP_PROVIDERS添加到提供者数组中。

顺便说一句,你不需要在你的构造函数中注入,你只需要做:

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