首页 文章

离子/角度2依赖注入根据模式不起作用

提问于
浏览
-1

我正在遵循依赖注入模式:http://devdocs.io/angular~2_typescript/cookbook/dependency-injection

我的代码看起来像这样:

MyService.ts

import { Injectable } from '@angular/core';

@Injectable()
export class MyService {}

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { MyService } from '../services/MyService';

@Component({
  templateUrl: 'app.html',
  providers: [MyService]
})

export class MyApp {}

MyComponent.ts

import { Component } from '@angular/core';

@Component({
  selector: 'theComponent',
  templateUrl: 'theComponent.html'
})
export class thisComponent {
  constructor(private thisService: MyService) {}

我收到以下错误:找不到名称'MyService' .

我已经检查过以确保“emitDecoratorMetadata”:true

我也试过公共,私人和公共/私人的额外的discriptor,我每次都得到相同的错误 .

1 回答

  • 1

    import 进入您的类文件允许您使用其他文件/模块中的导出定义 . 您需要将类导入到使用该类定义的每个文件中 .

    所以在 thisComponent.ts 中,你需要包括

    从'./path/to/services/MyService'导入;

    有关在Typescript中执行的操作的详细信息,请参阅https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3.2

    这与Angular2中的Modules的导入属性不同,后者涉及依赖链和注入器 .

相关问题