2015-12-16 142 views
2

玩弄Angular 2並試圖讓這個簡單的代碼工作。 但我不斷收到一個錯誤信息:Angular 2錯誤:

EXCEPTION: Cannot resolve all parameters for Tab(undefined). Make sure they all have valid type or annotations.

就NG2是不是在C onstructor(tabs:Tabs) {…注入構造

這裏是整個代碼:

///<reference path="../../typings/zone.js/zone.js.d.ts"/> 

import {Component, Input} from 'angular2/core'; 

@Component({ 
    selector: 'tab', 
    template: ` 
    <ul> 
     <li *ngFor="#tab of tabs" (click)="selectTab(tab)"> 
     {{tab.tabTitle}} 
     </li> 
    </ul> 
    <ng-content></ng-content> 
    `, 
}) 
export class Tab { 
    @Input() tabTitle: string; 
    public active:boolean; 
    constructor(tabs:Tabs) { 
     this.active = false; 
     tabs.addTab(this); 
    } 
} 

@Component({ 
    selector: 'tabs', 
    directives: [Tab], 
    template: ` 
    <tab tabTitle="Tab 1"> 
     Here's some content. 
    </tab> 
    `, 
}) 

export class Tabs { 
    tabs: Tab[] = []; 
    selectTab(tab: Tab) { 
     this.tabs.forEach((myTab) => { 
      myTab.active = false; 
     }); 
     tab.active = true; 
    } 

    addTab(tab: Tab) { 
     if (this.tabs.length === 0) { 
      tab.active = true; 
     } 
     this.tabs.push(tab); 
    } 
} 

TX

肖恩

回答

-1

你有兩個soluti附件: 在引導全球注入你的標籤類:

bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]); 

在注射局部標籤與結合特性,

@Component({ 
    selector: 'tab', 
    bindings: [Tabs], // injected here 
    template: ` 
    <ul> 
     <li *ngFor="#tab of tabs" (click)="selectTab(tab)"> 
    [...] 
5

那是因爲你的Tabs類是你Tab類和classes in javascript aren't hoisted後確定。

所以你必須使用forwardRef引用尚未定義的類。

export class Tab { 
    @Input() tabTitle: string; 
    public active:boolean; 
    constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) { 
     this.active = false; 
     tabs.addTab(this); 
    } 
} 
+0

或者聲明兩個模塊/名稱空間中的類。這允許你持有對包含實際類的對象的引用,並且在Angular來解除引用這些類時,它們將被創建。 –

+0

謝謝!!!!沒有考慮訂購,所以習慣於在es3中使用功能和標準提升 – born2net