2016-11-30 43 views
-1

我從依賴注入模式如下:http://devdocs.io/angular~2_typescript/cookbook/dependency-injection離子/角2依賴注入工作不根據模式

我的代碼如下所示:

MyService.ts

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

@Injectable() 
export class MyService {} 

應用.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」:真

我也試過在公共,私人和不放過額外discriptor公共/私營,每次我得到同樣的錯誤。

+0

看起來像這個組件缺少導入。 (從'../ services/MyService';''import'{MyService};')這是你真實的代碼嗎? – Fiddles

+0

@Fiddles,謝謝你的迴應。我在這裏以一個可怕的細節慢慢地死去。這是我的代碼的簡化版本。你爲什麼問,或者你認爲缺少什麼?爲什麼我需要在MyComponent中導入MyService,我認爲這已經通過app.component完成了。請澄清。 – rashadb

+1

@誰給了我-1,請解釋出了什麼問題。將文件路徑導入到服務的詳細信息不在文檔中。鑑於我現在不是唯一的新手學習Angular 2,我相信會有其他人陷入這個陷阱。希望我已經救了他們一些時間。 – rashadb

回答

1

import進入類文件允許您使用從其他文件/模塊導出的定義。您需要將該類導入到使用該類定義的每個文件中。

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

import { MyService } from './path/to/services/MyService';

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3.2更多信息什麼這打字稿

做這從模塊的Angular2,進口性質不同,其是關於依賴鏈和注入器。

+0

感謝工作,但如果我仍然需要將其導入到其他地方,那麼在創建根app.component.ts文件並將其導入時有什麼意義? – rashadb

+0

簡短版本,是您需要將定義導入到文件以便能夠在該文件中使用它。 – Fiddles