2015-06-11 29 views
6

我打算通過angular2.0演示應用程序,但似乎注射器不從構建24工作,並給我錯誤爲
「原始錯誤:無法解析MyAppComponent的所有參數。確保他們都有有效的類型或註釋。「
,直到建立23其工作正常,請幫助我的問題
下面是演示代碼,我提出了從最初的幾個操作只是爲了學習目的injectables不能工作在角2.0最新版本26

import {Component, View, bootstrap, NgFor} from 'angular2/angular2'; 


module foo{ 
    class FriendsService { 
    names: Array<string>; 
    constructor() { 
     this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana","Kai"]; 
    } 
} 


@Component({ 
    selector: 'array', 
    injecetables: [FriendsService] 

}) 
@View({ 
     template: '<p>My name: {{ myName }}</p><p>Friends:</p><ul><li *ng-for="#name of names">{{ name }}</li></ul>', 
     directives: [NgFor] 
}) 
    export class arrayComponent { 
    myName: string; 
    names: Array<string>; 

    constructor(friendsService: FriendsService) { 
     this.myName = 'Alice'; 
     this.names = friendsService.names; 
    } 
    } 
} 

bootstrap(foo.arrayComponent); 

回答

2

injectables新的語法是appInjector

嘗試:

@Component({ 
    selector: 'array', 
    appInjector: [FriendsService] 
}) 

而且,你會想改變你的進口ComponentView到:

import {ComponentAnnotation as Component, ViewAnnotation as View} from "angular2/angular2"; 
+1

以上解決方案不工作仍然給我同樣的錯誤,還有什麼我在上面的代碼中缺少 –

+1

'appInjector'已被刪除@ alpha.29,此解決方案將不再工作。現在必須使用'hostInjector'或'viewInjector' – shmck

+3

我有上面提到的同樣的問題,我已經嘗試了hostInjector和viewInjector,但仍然是相同的錯誤。你能指出一些東西,說明如何正確使用這些東西嗎? – davertron

0

module foo{ class FriendsService {...

FriendsService類是一個模塊,它是一個問題中定義有兩種方式:

  1. 類別需要從模塊導出,使其的foo
  2. 外部可見的當引用FriendsSerivce你不指定它是foo模塊內。

我會建議完全刪除foo模塊,而不是依靠amd/commonjs中的模塊模式。這意味着你不需要導出類(假設它們在同一個文件中),而且你不需要改變組件中的類的引用。

0

您的FriendsService在模塊中被抽象並且未被導出,這就是爲什麼arrayComponent無法訪問它並引發錯誤的原因。

您只需將模塊取出並在同一範圍內將foo標記爲arrayComponent即可。

此外,由於arrayComponent不是foo的一部分,所以在最後的引導程序是錯誤的。只要有它是

bootstrap(arrayComponent)

,它應該是罰款。

7

看起來the currently latest angular2, alpha-35,bindings代替appInjector

像這樣:

import {FriendsService} from 'FriendsService'; 

@Component({ 
    selector: 'array', 
    bindings: [FriendsService] 
}) 

我也必須明確出口FriendsService

export class FriendsService { 

Complete code example here

+0

@ klas-melbourn謝謝!我注意到你沒有使用引導中的'bootstrap()' - 是有原因的嗎?有'出口'代替? – ghchinoy

+1

@ghchinoy我在'app.ts'主文件中使用'bootstrap'。你只需要做一次,而不是每個'.ts'文件。 –

+0

不錯,除此之外,沒有任何工作! – Maxime

2

在角2有應用程序範圍的噴油器,然後有分量注射器。

如果你只是想在您的整個應用FriendsService的一個實例,則包括它引導()數組中:

@Component({ 
    // providers: [FriendsService], 
    ... 

bootstrap(App, [FriendsService]) 

如果你寧願每個組件一個實例,使用providers陣列中的組件的配置對象,而不是:

@Component({ 
    providers: [FriendsService ], 
    ... 

bootstrap(App, []) 

Plunker

有關更多信息,請參閱Hierarchical Injectors文檔。

相關問題