Angular 2 error:

2020-04-16 02:17发布

问题:

Playing around with Angular 2 and trying to get this simple code working. yet I keep getting an error of:

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

As far ng2 is not injecting in constructor(tabs:Tabs) {… into the constructor

Here is the entire code:

///<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

Sean

回答1:

That's because your Tabs class is defined after your Tab class and classes in javascript aren't hoisted.

So you have to use forwardRef to reference a not yet defined class.

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


回答2:

You have two solutions: Inject your Tabs class globally at bootstrap:

bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]);

On inject Tabs locally with a binding property,

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


标签: angular