2016-03-08 41 views
1

我有以下angular2應用程序注入簡單的依賴關係,它不起作用。我錯過了什麼?Angular2簡單的DI不工作

這裏的錯誤:

EXCEPTION: Cannot resolve all parameters for 'AppComponent'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AppComponent' is decorated with Injectable. 

,代碼:

import {Component} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser'; 

class DataService { 
    items: Array<any>; 

    constructor() { 
     this.items = [ 
      { name: 'Christoph Burgdorf' }, 
      { name: 'Pascal Precht' }, 
      { name: 'thoughtram' } 
     ]; 
    } 

    getItems() { 
     return this.items; 
    } 
} 


@Component({ 
    selector: 'app', 
    providers: [DataService], 
    template: ` 
    <ul> 
     <li *ngFor="#item of items">{{item.name}}</li> 
    </ul> 
    ` 
}) 
class AppComponent { 
    items: Array<any>; 
    constructor(dataService: DataService) { 
     this.items = dataService.getItems(); 
    } 
} 

bootstrap(AppComponent, []); 
+0

你'DataService'和'AppComponent'在同一個文件,並在文件中相同的順序? –

+0

其全部一個文件 – Tucker

+0

並且以相同的順序? –

回答

1

無法重現。我加了你的代碼到Plunker

https://plnkr.co/edit/0DTjG5?p=preview

,它似乎很好地工作或不@Injectable()

建議始終將@Injectable()添加到服務,但只有在服務具有構造函數參數時才需要。

.

+1

感謝您的plnkr。我認爲我的項目設置有問題。我基本上覆制了你的