2015-12-16 169 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