【问题标题】:Inject custom service in another service in Angular 2在Angular 2的另一个服务中注入自定义服务
【发布时间】:2016-07-21 08:56:57
【问题描述】:

我想将服务注入另一个服务。我在注入标准 Angular 服务(Http 等)时没有任何问题,但是当我尝试注入自己的服务时遇到异常。

例子:

我的服务:

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

另一个服务:

import {Injectable} from 'angular2/core';

@Injectable()
export class AnotherService {

   constructor() { }
   get() { return 'hello'); }

}

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

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

谢谢!

【问题讨论】:

    标签: javascript dependency-injection angular ionic2


    【解决方案1】:

    您应该阅读 Angular 2 文档。您的确切问题在此处的角度文档中进行了解释:https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service

    您必须将您的服务添加到提供程序数组中。您可以使用 Http 而不这样做的唯一原因是 Ionic 为您将其放在提供程序数组中。如果你使用的是原生 Angular 2,你仍然需要将 HTTP_PROVIDERS 添加到 providers 数组中。

    作为旁注,你不需要在你的构造函数中注入,你可以这样做:

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

    【讨论】:

    • 非常感谢!现在可以了!我刚刚在组件的提供者中指定了AnotherService。我应该更仔细地阅读文档。
    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多